![](/img/trans.png)
[英]How to extract text from webdriver elements found through xpath using Selenium and Python
[英]Extract link from XPath using Selenium Webdriver and Python?
我對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表示(據我所知)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.