使用SeleniumWebDriver和Python从XPath提取链接?
我对Seleniun WebDriver和Python还比较陌生,我的问题可能有点基本 因此,我有以下HTML代码:使用SeleniumWebDriver和Python从XPath提取链接?,python,python-2.7,selenium-webdriver,Python,Python 2.7,Selenium Webdriver,我对Seleniun WebDriver和Python还比较陌生,我的问题可能有点基本 因此,我有以下HTML代码: <a class="wp-first-item" href="admin.php?page=account">Account</a> 或 似乎不起作用,导致: AttributeError: 'WebElement' object has no attribute 'link' 我希望结果类似于“admin.php?page=account”您可以使用
<a class="wp-first-item" href="admin.php?page=account">Account</a>
或
似乎不起作用,导致:
AttributeError: 'WebElement' object has no attribute 'link'
我希望结果类似于
“admin.php?page=account”
您可以使用get\u属性
:
element = driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a")
href = element.get_attribute('href')
print href
通常,我使用Selenium导航到一个页面,检索源代码并使用以下内容对其进行解析:
从美化组导入美化组
#在当前页面上
source=driver.page\u source
汤=美汤(来源)
href=soup(“”,{'id':'toplevel_page_menu'})[0]('ul')[0]('li')[2]('a')[0]['href']
不幸的是,BeautifulSoup不支持xpath,因此以上是xpath的BS表示(据我所知)。我是否需要导入一些异国情调才能使get_attribute()工作?在末尾添加/@href似乎不起作用。请尝试使用
element=driver。通过xpath(“./*[@id='toplevel\u page\u menu']/ul/li[2]/a”)查找元素。
然后使用get\u attribute
:打印元素。get\u attribute('href')
。那可能行得通。很抱歉造成混淆,我通常不通过Selenium提取源数据。就像我说的,我通常用BS。
AttributeError: 'WebElement' object has no attribute 'link'
element = driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a")
href = element.get_attribute('href')
print href
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']