【问题标题】:How to click on the button when the textContext contains leading and trailing white-space characters?当 textContext 包含前导和尾随空白字符时如何单击按钮?
【发布时间】:2019-05-31 20:44:53
【问题描述】:

我正在尝试使用 Selenium 和 python 单击以下按钮:

<button type="submit" tabindex="4" id="sbmt" name="_eventId_proceed">
          Einloggen
</button>

这只是一个简单的按钮,如下所示:

代码:

driver.find_element_by_id('sbmt').click()

这会导致以下异常:

selenium.common.exceptions.ElementNotInteractableException: Message:
Element <button id="sbmt" name="_eventId_proceed" type="submit">
could not be scrolledinto view

所以,我尝试在单击按钮之前使用 ActionChains(driver).move_to_element(driver.find_elements_by_id('sbmt')[1]).perform() 滚动到元素。

(使用[1] 访问第二个元素,因为第一个元素会导致selenium.common.exceptions.WebDriverException: Message: TypeError: rect is undefined 异常。)。

然后我用了

wait = WebDriverWait(driver, 5)
submit_btn = wait.until(EC.element_to_be_clickable((By.ID, 'sbmt')))

为了等待按钮可点击。这些都没有帮助。

我也用过driver.find_element_by_xpath等,我用Firefox和Chrome测试过。

如何点击按钮而不出现异常?

任何帮助将不胜感激

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    要在元素上调用 click(),您需要首先使用 WebDriverWaitexpected_conditions 以使 元素可点击,您可以使用以下解决方案:

    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='sbmt' and normalize-space()='Einloggen']"))).click()
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    【讨论】:

    • 当您可以直接使用带有 id 的By.ID 时,为什么还要引入复杂的 XPATH?
    • OP 已经表示他尝试了基本相同的解决方案.. 为什么这有帮助?
    • @CoreyGoldberg 根据 submit 类型的&lt;button&gt; 元素的属性,很明显有多个元素具有 id 属性作为sbmt。在这些情况下,使用 By.ID 可能对 OP 没有帮助。所以我决定加入innerText。因此是 XPATH。
    • 在你的回答中解释一下可能会很好
    • @CoreyGoldberg 这很有帮助,因为它向我展示了如何正确使用By.XPATH。我尝试使用它,但我以错误的方式指定它
    猜你喜欢
    • 2019-06-02
    • 2011-01-16
    • 2023-02-14
    • 2021-03-31
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多