Strawbewy
Strawbewy

Reputation: 33

How to get the list specific multiple links in Selenium python

I need to get list of links from a webpage it has href="/example/*" it doesn't have any specific class name or id.

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print(elem.get_attribute("href"))

Right now, I'm getting all the links in the page.

Upvotes: 0

Views: 45

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146550

You can either do the filter in the xpath itself (recommended approach)

elems = driver.find_elements_by_xpath("//a[contains(@href,'/example/')]")
for elem in elems:
    print(elem.get_attribute("href"))

or you can fetch and then filter

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    href = elem.get_attribute("href")
    if '/example/' in href:
       print(href)

Upvotes: 1

Related Questions