如何使用Selenium和Python提取元素的href属性

如何使用Selenium和Python提取元素的href属性,python,selenium-webdriver,Python,Selenium Webdriver,我想在“下一步比赛”部分的HTML中抓取URL 以下是HTML的摘录: <a ng-href="/racing/2020-07-31/MACKAY/MAC/R/8" href="/racing/2020-07-31/MACKAY/MAC/R/8"><i ng- 我尝试使用xpath查找元素,但无法获得所需的URL 我的代码: driver = webdriver.Firefox(executable_path=r"C:\Us

我想在“下一步比赛”部分的HTML中抓取URL

以下是HTML的摘录:

<a ng-href="/racing/2020-07-31/MACKAY/MAC/R/8" href="/racing/2020-07-31/MACKAY/MAC/R/8"><i ng- 
我尝试使用xpath查找元素,但无法获得所需的URL

我的代码:

driver = webdriver.Firefox(executable_path=r"C:\Users\Harrison Pollock\Downloads\Python\geckodriver-v0.27.0-win64\geckodriver.exe")
driver.get('https://www.tab.com.au/')
elements = driver.find_elements_by_xpath('/html/body/ui-view/main/div[1]/ui-view/version[2]/div/section/section/section/race-list/ul/li[1]/a')
for e in elements:
    print(e.text)
可能您想使用get_属性代替.text。文件

是的,您可以根据需要使用getAttributeattributeLocator函数

selenium.getAttribute(//xpath@href);
指定需要知道其类别的元素的Xpath。

HTML中的值/racing/2020-07-31/MACKAY/MAC/R/8是href属性的值,而不是innerText

解决方案 您需要使用get_attributehref,而不是使用text属性,有效的代码行将是:

elements = driver.find_elements_by_xpath('/html/body/ui-view/main/div[1]/ui-view/version[2]/div/section/section/section/race-list/ul/li[1]/a')
for e in elements:
    print(e.get_attribute("href"))

您可以尝试对变量进行拆分,如字符串。拆分“”[3]请发布代码试用版?我已尝试使用xpath查找元素,但无法获取所需的URL。会发生什么?
selenium.getAttribute(//xpath@href);
elements = driver.find_elements_by_xpath('/html/body/ui-view/main/div[1]/ui-view/version[2]/div/section/section/section/race-list/ul/li[1]/a')
for e in elements:
    print(e.get_attribute("href"))