从ID找到的元素中获取href - Python - Selenium

时间:2017-08-25 15:54:23

标签: html python-3.x selenium

这是我的代码:

dispatch_button = browser.find_elements_by_xpath("//*[contains(@id, 'alarm')]")
href = dispatch_button.get_attribute('href')
print(href)

这是我正在使用的HTML:

<a href="/missions/12357831" class="btn btn-default btn-xs lightbox-open" id="alarm_button_12357831"> Dispatch</a>

ID和href都包含一个更改的数字,这就是我使用部分ID找到它的原因。

我完全难过,因为我无法理解为什么我会收到此错误:

 href = dispatch_button.get_attribute('href')
 AttributeError: 'list' object has no attribute 'get_attribute'

我正在尝试通过其部分ID找到dispatch_button,然后使用其href。

1 个答案:

答案 0 :(得分:0)

如果您想获得单个WebElement,则应使用find_element_by_xpath()而不是find_elements_by_xpath()

dispatch_button = browser.find_element_by_xpath("//*[contains(@id, 'alarm')]")
href = dispatch_button.get_attribute('href')

或者如果要处理由指定选择器匹配的多个元素:

dispatch_buttons = browser.find_elements_by_xpath("//*[contains(@id, 'alarm')]")
hrefs = [dispatch_button.get_attribute('href') for dispatch_button in dispatch_buttons]

您也可以尝试通过link_text找到所需的锚点:

dispatch_button = browser.find_element_by_link_text("Dispatch")