【问题标题】:Python Selenium find element which contains specific textPython Selenium 查找包含特定文本的元素
【发布时间】:2021-08-12 02:56:56
【问题描述】:

我有问题。我想找到几个使用 Selenium 的网站的登录页面。为此,我尝试转到页面并单击带有“登录”、“登录”等文本的按钮。这适用于 Netflix。示例:

代码网站:Netflix.com

<a href="/login" class="authLinks redButton" data-uia="header-login-link">Sign In</a>

我的代码来检测按钮:


result = "https://www.microsoft.com"

driver.get(result)

elem = driver.find_element_by_link_text('Sign In').click

print(driver.current_url) # returns the website: https://www.netflix.com/de-en/login

现在我在 Microsoft.com 网站上进行尝试。网站代码作为图片:

如果我现在将包含查询更改为:

driver.find_element_by_link_text('Sign in').click # small "in"

Selenium 没有找到任何元素。我尝试了 Selenium 提供的许多不同选项,例如:

  1. find_element_by_id
  2. find_element_by_name
  3. find_element_by_link_text
  4. ...

例如:[https://selenium-python.readthedocs.io/locating-elements.html]

我的目标是使用“登录、登录”等文本信息来找到按钮并按下它。

非常感谢您的帮助

【问题讨论】:

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


    【解决方案1】:

    看到这里的问题是Netflix.com,你有一个这样的HTML:

    <a href="/login" class="authLinks redButton" data-uia="header-login-link">Sign In</a>
    

    看标签,是a,是HTML中的锚标签。

    find_element_by_link_textfind_element_by_partial_link_text 在锚标记之间查找文本。

    但是当你去Microsoft.com

    <div class="mectrl_header_text mectrl_truncate">Sign in</div>
    

    Sign in 包裹在 div 中。所以find_element_by_link_textfind_element_by_partial_link_text 将不起作用。

    相反,您可以尝试使用以下 xpath :-

    //div[text()='Sign in']
    

    在代码中:-

    driver.find_element_by_xpath("//div[text()='Sign in']").click()
    

    或者您也可以尝试使用显式等待:-

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[text()='Sign in']"))).click()
    

    【讨论】:

      【解决方案2】:

      正如 Cruisepandey 针对这两种特殊情况所描述的那样,find_element_by_link_text 在某些情况下会起作用,但在其他一些情况下则不会。
      虽然通过它的文本定位元素将适用于所有这些情况。
      所以我从不使用find_element_by_link_text 或部分文本方法,只使用基于元素文本的find_element_by_xpath 方法,它工作正常。
      在您的情况下,您可以使用

      WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[text()='Sign in']"))).click()
      

      这样会更简单、稳定、可靠。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-01
        • 2020-09-05
        • 1970-01-01
        • 2020-01-13
        • 1970-01-01
        • 2013-08-26
        • 2016-12-10
        相关资源
        最近更新 更多