【问题标题】:python selenium webdriver is unable to locate elements with explicit waitpython selenium webdriver 无法找到具有显式等待的元素
【发布时间】:2020-10-29 03:46:50
【问题描述】:

我正在尝试使用 python selenium 自动在 nike.com 上进行购买,但由于常见错误 - 无法找到元素,我的程序总是失败。最初,我尝试使用<driver>.find_element_by_xpath(<xpath>),但有时无法及时找到元素,因此我决定使用WebdriverWait:

try: 
        
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='placeorder']/div/div[1]/button")))
        #(driver.find_element("//button[text() = 'Place Order']"))
        print("found the button!")
except:
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='payment']/div/div[1]/div[2]/div[5]/button")))
        #(driver.find_element_by_xpath("//button[text() = 'Continue To Order Review']"))
        print("found the alternate button")

我正在使用 try/except 块,因为我需要完成购买的按钮并不总是相同的。在一种情况下,它可能是一个表示“下订单”的按钮,或者它可能是一个不同形状的按钮,表示“继续订购审查”。他们在这里:

[

不幸的是,在这些情况下,仍然没有单击(或找到)按钮,并且脚本会引发 TimeoutException。我怎样才能绕过这种类型的错误?我一直在查看类似人的错误,但似乎找不到有效的解决方案。

【问题讨论】:

  • 所以你已经瞄准了那些“箱子”(按钮可以改变的地方),但驱动程序仍然没有通过上面的位找到它们?
  • @chrymxbrwn 对了,上面的sn-p,驱动还是找不到。我也验证了它们各自的 xpath

标签: python selenium selenium-webdriver


【解决方案1】:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Place Order']|//button[text()='Continue To Order Review']"))) 

您可以使用 |作为 or 来找到一个或另一个。

【讨论】:

  • 感谢您的建议,但这也会返回相同的错误。这可能与硒有关吗?我一直无法选择这些按钮,但我使用驱动程序与之交互的其他元素有时会起作用,有时不会。
  • 看来可能有 iframe。您必须切换到 iframe 才能访问它们。
  • 管道是一个不错的技巧。它与本质上链接它们的作用相同还是行为不同?
  • 基本上相当于 OR。
猜你喜欢
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多