如何使用 Selenium 和 Python 从元素获取链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20850539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:23:20  来源:igfitidea点击:

How to get link from elements with Selenium and Python

pythonselenium

提问by jacob501

Let's say all Author/username elements in one webpage look like this... How can I get to the href part using python and Selenium? users = browser.find_elements_by_xpath(?)

假设一个网页中的所有作者/用户名元素看起来像这样......我如何使用 python 和 Selenium 到达 href 部分?用户 = browser.find_elements_by_xpath(?)

<span>

    Author: 

    <a href="/account/57608-bob">

        bob

    </a>

</span>

Thanks.

谢谢。

采纳答案by falsetru

Use .//span[contains(text(), "Author")]/aas xpath expression.

使用.//span[contains(text(), "Author")]/a的XPath表达式。

For example:

例如:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://jsfiddle.net/9pKMU/show/')
for a in driver.find_elements_by_xpath('.//span[contains(text(), "Author")]/a'):
    print(a.get_attribute('href'))

回答by WKPlus

Use find_elements_by_tag_name('a')to find the 'a' tags, and then use get_attribute('href')to get the link string.

find_elements_by_tag_name('a')找到的“a”标记,然后用get_attribute('href')得到的链接字符串。