Home > front end >  Find all elements with href tag containing certain text with Selenium and Python
Find all elements with href tag containing certain text with Selenium and Python

Time:03-01

Lets say I have html code with three links

<a href="hey123"> Whatever </a>
<a href="hey321"> Whatever </a>
<a href="hi123"> Whatever </a>

and I want to use selenium to find all elements which have a href tag which includes the string "hey" (in this case the first two links). How would I write python Selenium code which accomplishes this?

CodePudding user response:

This works:

all_href = driver.find_elements(By.XPATH,  "//*[contains(@href, 'hey')]")
print(len(all_href)

CodePudding user response:

This XPath will do this work:

"//a[contains(@href,'hey')]"

To use that with Selenium you will need a find_elements or findElements method, depends on the language binding you use with Selenium.
For Selenium in Python this will give you the list of all such elements:

all_hey_elements = driver.find_elements(By.XPATH,  "//a[contains(@href, 'hey')]")
  • Related