gpt4 book ai didi

python - 使用 Selenium Webdriver 和 Python 从 XPath 中提取链接?

转载 作者:太空狗 更新时间:2023-10-29 21:32:09 31 4
gpt4 key购买 nike

我是 Seleniun WebDriver 和 Python 的新手,我的问题可能比较基础。

所以,我有以下 HTML 代码:

<a class="wp-first-item" href="admin.php?page=account">Account</a>

并且我正在尝试从中提取 href,作为 XPath 的手段,知道它的 XPath 是 ".//*[@id='toplevel_page_menu']/ul/li[2]/a".

我该怎么做?

driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a").link

driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a").href

似乎不起作用,导致:

AttributeError: 'WebElement' object has no attribute 'link'

我希望结果类似于 "admin.php?page=account"

最佳答案

你可以使用get_attribute:

element = driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a")
href = element.get_attribute('href')
print href

通常我使用 Selenium 导航到页面,检索源代码并使用 BeautifulSoup 解析它:

from BeautifulSoup import BeautifulSoup

# On the current page
source = driver.page_source
soup = BeautifulSoup(source)

href = soup('<the tag containing the anchor>',{'id':'toplevel_page_menu'})[0]('ul')[0]('li')[2]('a')[0]['href']

不幸的是,BeautifulSoup 不支持 xpath,所以上面是你的 xpath 的 BS 表示(据我所知)。

关于python - 使用 Selenium Webdriver 和 Python 从 XPath 中提取链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15388057/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com