在python中使用selenium遍历div后获取href链接

时间:2016-07-05 20:49:57

标签: python selenium

我是Selenium的新手..我正在尝试获取两个div元素中存在的href链接

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

如何获得href链接?我试过了

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")

但它不起作用

1 个答案:

答案 0 :(得分:1)

试试这个: 假设您的浏览器驱动程序名为“driver”,并且所有元素的属性都是唯一的。

  • Xpath:

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

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