亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

千巷貓影 2023-04-18 16:01:29
我想在www.tab.com.au的“Racing-Next to Go”部分的 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- 我只想抓取 HTML 的最后一點,它是一個鏈接,所以:/racing/2020-07-31/MACKAY/MAC/R/8我嘗試使用 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)
查看完整描述

3 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

可能您想使用get_attributeinsted of .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"))


查看完整回答
反對 回復 2023-04-18
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

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


解決方案

而不是使用您需要使用的文本get_attribute("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"))


查看完整回答
反對 回復 2023-04-18
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

是的,您可以根據需要使用getAttribute(attributeLocator)函數。

selenium.getAttribute(//xpath@href);

指定您需要知道其類別的元素的 Xpath。


查看完整回答
反對 回復 2023-04-18
  • 3 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號