【问题标题】:How to find an element by href value using selenium python?如何使用 selenium python 通过 href 值查找元素?
【发布时间】:2016-01-14 07:40:23
【问题描述】:

我有一个锚标记的 href 值,它只有 href 值作为属性。现在我想在页面中找到与我的 href 值具有相同值的元素并单击它。我找不到使用标准硒方法的任何方法。我该怎么做? 基本上这些是我找到的功能,但似乎我不能使用其中任何一个:

find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    您可以使用 find_element_by_xpath 功能。

    driver.find_element_by_xpath('//a[@href="'+url+'"]')
    

    【讨论】:

    • 如果我的 url 在变量中怎么办?
    • 而不是将其作为字符串添加到那里。
    • 请记住,如果您有多个具有相同 URL 的链接,则可能会返回一个数组
    • 这个效果很好,只要页面已经加载了所有内容
    【解决方案2】:

    你可以试试这个:

    driver.find_element_by_xpath('//a[contains(@href,"href")]')
    

    【讨论】:

      【解决方案3】:

      您可以通过 CSS 选择器找到元素,就像使用 vanilla CSS 一样:

      link = driver.find_element_by_css_selector('[href^=http://somelink.com/]')
      

      你也可以find the element by the link text:

      link = driver.find_element_by_partial_link_text('somelink')
      

      【讨论】:

        【解决方案4】:

        我有一个名为“您的个人资料”的按钮,带有此 html 行

        <a href="/registration/profile.html" rel="follow">Your Profile</a>
        

        到目前为止,我一直在尝试 find_element_by 链接、xpath、css 选择器,但没有成功。它返回错误无法找到元素。

        browser.find_element_by_partial_link_text("Your Profile")
        
        browser.find_element_by_xpath('//a[contains(@href,"registration/profile.html")]')
        

        谢谢

        【讨论】:

          【解决方案5】:

          按钮的样子

          <a href="server_export.php" class="tab">&nbsp;Export</a>
          

          并且因为可能文本已被翻译,我们不能使用搜索文本Export,所以我们必须搜索例如对于server_export 内的href 并且可以例如点击它

          driver.find_element(By.XPATH,'//a[contains(@href,"server_export")]').click()
          

          注意:使用推荐的find_element(By.xxxxx, ...) 格式。

          【讨论】:

            猜你喜欢
            • 2018-12-24
            • 2015-04-18
            • 2018-10-20
            • 2013-04-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多