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

jac*_*501 8 python selenium

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

<span>

    Author: 

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

        bob

    </a>

</span>
Run Code Online (Sandbox Code Playgroud)

谢谢.

fal*_*tru 11

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

例如:

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'))
Run Code Online (Sandbox Code Playgroud)


WKP*_*lus 9

使用find_elements_by_tag_name('a')找到的"a"标记,然后用get_attribute('href')得到的链接字符串.