【问题标题】:How to locate an element with reference to a text within the HTML using Selenium and Python如何使用 Selenium 和 Python 参考 HTML 中的文本定位元素
【发布时间】:2019-04-03 17:43:10
【问题描述】:

我有一个需要循环访问的 URL 列表。所有 URL 都登陆到该站点的主页。我需要在主页上的某处找到指向该网站另一部分的链接,其中包含“寻找医生”,因为我需要导航到每个网站上的“寻找医生”部分。

我尝试使用 XPath contains 查找元素。

driver.find_element_by_xpath("//*[contains(text(), 'Find a Doctor')]").get_attribute('href')

这是 HTML 在一个特定 URL 上的样子,但布局在另一个 URL 上可能会有所不同,因为我正在循环访问各种链接。

<a href="/search/custom.asp?id=2671" tabindex"-1">
<span> Find a Doctor </span>
</a>

问题是字符串在 span 内,因此 span 没有 href。

我希望输出是网站查找医生部分的 href,但返回的是一个空字符串。

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver xpath xpath-1.0


    【解决方案1】:

    正如您正确提到的,文本 Find a Doctor 位于 &lt;span&gt; 标记内,并且没有 href 属性。但是 preceding &lt;a&gt; 标记包含 href 属性。因此,要提取href 属性,您可以使用以下任一解决方案:

    • XPath 1

      my_href = driver.find_element_by_xpath("//span[contains(., 'Find a Doctor')]//preceding::a[1]").get_attribute('href')
      
    • XPath 2

      my_href = driver.find_element_by_xpath("//span[normalize-space()='Find a Doctor']//preceding::a[1]").get_attribute('href')
      

    【讨论】:

      【解决方案2】:

      你所要做的就是像下面那样去父母那里。

      driver.find_element_by_xpath("//*[contains(text(), 'Find a Doctor')]/parent::a").get_attribute('href')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        • 1970-01-01
        • 2019-09-06
        • 1970-01-01
        • 2020-05-28
        相关资源
        最近更新 更多