【问题标题】:How to click the second element if the first element is not clickable using Python Selenium如果使用 Python Selenium 无法单击第一个元素,如何单击第二个元素
【发布时间】:2022-01-02 22:54:56
【问题描述】:

如果使用 Python Selenium 无法点击第一个元素,如何点击第二个元素

代码试验:

if self.driver.find_element(By.CSS_SELECTOR, ".estimator-container:nth-child(3) .btn").is_not_clicked():
    self.driver.find_element(By.LINK_TEXT, "Dont have the Plate?").click();

【问题讨论】:

  • 你能分享你页面的 HTML 吗?如果可能,您也可以分享网址
  • 这是在 python 上我想添加这个命令,当我做测试时如果不点击这个按钮点击另一个按钮
  • 是的,首先你需要检查,这个按钮是否可以点击,如果结果是no,你可以点击另一个按钮。
  • 是的,但我想知道如何在 selenium 中用 python 编写它

标签: python selenium selenium-webdriver webdriverwait try-except


【解决方案1】:

要点击任何 可点击 元素,您需要为 element_to_be_clickable() 诱导 WebDriverWait 将代码块包裹在 try-except{} 块中,您可以使用以下Locator Strategies

try:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".estimator-container:nth-child(3) .btn"))).click()
    print("First element was clicked")
except TimeoutException:
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Dont have the Plate?"))).click()
    print("Second element was clicked")

注意:您必须添加以下导入:

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

【讨论】:

  • 我想在输入字段后使用 If 为此原因,我按下按钮它被禁用,因为输入错误(我故意这样做是为了选择另一个按钮)所以我点击另一个按钮。有意义吗?
  • 你确定你有is_not_clicked()方法/属性吗?
  • 为此我想问我应该如何编写代码只有 xparh 或 od 才能工作?
  • 我已经给你写好了代码
  • 是的,我看到了,但如果不尝试,我想使用除此之外的方法。这对我有很大帮助
猜你喜欢
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
相关资源
最近更新 更多