简体   繁体   English

python selenium webdriver无法通过显式等待定位元素

[英]python selenium webdriver is unable to locate elements with explicit wait

I am trying to automate making purchases on nike.com with python selenium, but my program always fails because of a common error - unable to locate element.我正在尝试使用 python selenium 在 nike.com 上自动进行购买,但我的程序总是因为一个常见错误而失败 - 无法定位元素。 Initially, I was trying to use <driver>.find_element_by_xpath(<xpath>) , but sometimes the elements were not available in time for them to be found, so I decided to use WebdriverWait:最初,我尝试使用<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")

I'm using a try/except block because the button that I need to complete the purchase is not always the same.我正在使用 try/except 块,因为我需要完成购买的按钮并不总是相同的。 In one case, it could be a button saying 'place order', or it could be a differently shaped button saying 'continue to order review.'在一种情况下,它可能是一个显示“下订单”的按钮,也可能是一个显示“继续订单审核”的不同形状的按钮。 Here they are:他们来了:

继续下单的图片

[ [继续订购评论按钮1的图片

Unfortunately, in these cases, the button is still not clicked (or found), and the script throws a TimeoutException.不幸的是,在这些情况下,仍然没有点击(或找到)按钮,并且脚本会抛出 TimeoutException。 How can I get around this type of error?我怎样才能解决这种类型的错误? I've been looking through similar people's errors, but I can't seem to find a solution that works.我一直在查看类似人的错误,但似乎找不到有效的解决方案。

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Place Order']|//button[text()='Continue To Order Review']"))) 

You can use |您可以使用 | as an or to find one or the other.作为一个或找到一个或另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM