如何使用Python在Selenium中查找元素中的所有href

时间:2018-02-15 04:43:37

标签: python selenium

我找到了一个元素,想要在这个元素中找到所有的href。我试图获得所有链接,但只获得了第一个链接。

element = driver.find_element_by_xpath("//div[@class='msg']/div[@class='']")
href = element.find_element_by_css_selector('a').get_attribute('href') #only get first link 

这样做的正确方法是什么?

非常感谢。

1 个答案:

答案 0 :(得分:2)

请参阅the Selenium docs

  

要查找多个元素(这些方法将返回一个列表)...

css的多元素版本为find_elements_by_css_selector

element = driver.find_element_by_xpath("//div[@class='msg']/div[@class='']")
hrefs = [x.get_attribute('href') for x in element.find_elements_by_css_selector('a')]