MrRobot9
MrRobot9

Reputation: 2684

get the href link after traversing through divs using selenium in python

I am new to Selenium.. I am trying to get the href link which is present inside two div elements

<div class="abc def">
     <div class="foo xyz">
          <a href="/watch123" ></a>
     </div>
</div>

How do I get the href link? I have tried

persons = []
for person in item.find_elements_by_class_name('abc.def'):
    title = person.find_element_by_xpath('.//div[@class="foo.xyz"]/a').text
    link = title.get_attribute("href")

but it does not work

Upvotes: 1

Views: 3025

Answers (1)

Yu Zhang
Yu Zhang

Reputation: 2149

Try this: assuming your browser driver is called "driver" and all your elements' attributes are unique.

  • Xpath:

    element = driver.find_element_by_xpath("//div[@class='foo xyz']/a")
    link = element.get_attribute("href")
    
  • Css selector:

    element = driver.find_element_by_css_selector("div[class='foo xyz']>a")
    link = element.get_attribute("href")
    

Upvotes: 4

Related Questions