【问题标题】:Extract link from XPath using Selenium Webdriver and Python?使用 Selenium Webdriver 和 Python 从 XPath 中提取链接?
【发布时间】:2013-03-13 14:25:52
【问题描述】:

我对 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"

【问题讨论】:

    标签: python python-2.7 selenium-webdriver


    【解决方案1】:

    你可以使用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 表示(据我所知)。

    【讨论】:

    • 我是否需要导入一些奇异的东西才能让 get_attribute() 工作?在末尾添加 /@href 似乎不起作用。
    • 尝试element = driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a"),然后使用get_attributeprint element.get_attribute('href')。那可能行得通。很抱歉造成混淆,我通常不通过 Selenium 提取源数据。就像我说的,我通常使用 BS。
    猜你喜欢
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多