【问题标题】:Python/Selenium - Can't get HREF value of a tagPython/Selenium - 无法获取标签的 HREF 值
【发布时间】:2017-05-27 12:35:41
【问题描述】:

所以我有这个 HTML 元素:

<h2 class="post-title">

    <a href="http://google.com" rel="bookmark">This a link to Google!</a>

</h2>

我正在使用driver.find_elements_by_class_name('post-title') 来查找这段 HTML。

但是我怎样才能只提取“href”标签的值呢?

我试过了:

driver.get_attribute('href')

返回“无”

谢谢

【问题讨论】:

标签: java python selenium selenium-chromedriver


【解决方案1】:

你有两个问题:

  • 您正在尝试查找 h2 元素而不是 a
  • 您正在尝试从WebDriver 实例中获取属性值

尝试下面的代码以获得所需的输出:

driver.find_element_by_css_selector('h2.post-title>a').get_attribute('href')

【讨论】:

    【解决方案2】:

    确实,标签为 h2 的兄弟没有 href 属性,这是您通过搜索元素 by_class_name('post-title') 定位的兄弟。它是兄弟&lt;a&gt;&lt;/a&gt;

    用 xpath 搜索呢?如果'post-title' 是唯一的类标识符,您可以按如下方式搜索您的元素

    xpth = "//*[@class='post-title']/a"
    a_element = driver.find_element_by_xpath(xpth)
    

    最后

    href = a_element.get_attribute('href')
    


    您可以(几乎)拥有的东西
    h2_element = driver.find_element_by_class_name('post-title')
    a_element = h2_element.find_element_by_tag_name("a")
    href = a_element.get_attribute('href')
    

    【讨论】:

      【解决方案3】:

      href 属于&lt;a&gt; 标签;所以首先你必须到达该元素,如下所示:

      elem = driver.find_element_by_xpath('//h2[@class="post-title"]/a')
      
      attribute_value = elem.get_attribute('href')
      

      【讨论】:

        猜你喜欢
        • 2019-01-09
        • 2021-05-20
        • 1970-01-01
        • 2021-07-30
        • 2021-06-12
        • 2012-03-17
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        相关资源
        最近更新 更多