我的明确等待我在哪里弄错了?预期条件wait.until语法?

时间:2019-02-19 11:59:44

标签: python selenium wait webdriverwait staleelementreferenceexception

我解决了以前的sys.argv问题(取决于.cmd文件如何调用脚本)。

现在我遇到了另一个麻烦:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

我对此有很多了解,但是我仍然很困惑如何处理它。

我的代码很简单:

while True:
    price = float(driver.find_elements_by_xpath("//td[@class='col-prix']")[0].text.strip()[:-1].replace(",","."))
    if a <= price <= b: break
    driver.find_elements_by_xpath("//button")[0].click()

有时我会得到:

Traceback (most recent call last):
  File "script.py", line 51, in <module>
    driver.find_elements_by_xpath("//button")[0].click()

(...)

File "C:\Python\Python37-32\lib\site-packages\selenium-3.141.0-py3.7.egg\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

有时:

Traceback (most recent call last):
  File "script.py", line 49, in <module>
    price = float(driver.find_elements_by_xpath("//td[@class='col-prix']")[0].text.strip()[:-1].replace(",","."))

(...)

  File "C:\Python\Python37-32\lib\site-packages\selenium-3.141.0-py3.7.egg\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

所以我有兴趣检查两者是否都存在(可见?)。

我试图实现一个简单的方法:

wait = WebDriverWait(driver, 60)
element = wait.until(EC.presence_of_element_located((By.XPATH,"//button")))

wait = WebDriverWait(driver, 60)
element = wait.until(EC.presence_of_element_located((By.XPATH,"//td[@class='col-prix']")))

但我仍然遇到相同的错误。

问题#1:我使用的语法正确吗?

问题2:这是否可以链接到两个元素都需要有谓词[0]的事实(如果是,我该如何在present_of_element_located中指定谓词)?

感谢您的帮助! ;-)


编辑

这是我的代码。

我有一个设置文件“ test.txt”,其中仅包含:

https://ticketplace.psg.fr/fr/recherche-place/668829,1,1:2:3:4:5:6:7:8:9:10:11:12:13:14:15,81,161

我有一个.cmd文件,其中仅包含:

start "test" "py" "test.py" "test.txt"

并且我有一个测试脚本“ test.py”:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from time import sleep
import datetime
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
import csv
import sys
from playsound import playsound
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(executable_path="chromedriver")
with open(str(sys.argv[1]), "r") as settings:
    for setting in settings:
        driver.get(setting.split(",")[0].strip())
        tickets=setting.split(",")[1]
        categories=setting.split(",")[2]
        minPrice=float(setting.split(",")[3].strip())
        maxPrice=float(setting.split(",")[4].strip())
        try:
            driver.find_element_by_css_selector(".accepte_cookie.bandeau_close").click()
            alert = driver.switch_to.alert
            alert.accept()
            sleep(1)
        except:
            pass
        try:
            driver.find_elements_by_xpath("//button")[0].click()
            driver.find_element_by_xpath("//li[@data-search-term="+tickets+"]").click()
            driver.find_elements_by_xpath("//button")[0].click()
            sleep(1)
            driver.find_elements_by_xpath("//button")[1].click()
            for categorieNumber in categories.split(':'):
                driver.find_element_by_xpath("//li[@data-search-term='cat. "+categorieNumber+"']").click()
            driver.find_elements_by_xpath("//button")[1].click()
            sleep(1)
        except:
            continue
        while True:
            hint = float(driver.find_elements_by_xpath("//td[@class='col-prix']")[0].text.strip()[:-1].replace(",","."))
            if minPrice <= hint <= maxPrice: break
            driver.find_elements_by_xpath("//button")[0].click()
            driver.find_elements_by_xpath("//button")[0].click()
            sleep(1)
        cat = driver.find_elements_by_xpath("//td[@class='col-cat']")[0].text
        print(datetime.datetime.now().strftime("%H:%M")+" - "+tickets+" tix "+cat+" at "+str(int(hint)))

1 个答案:

答案 0 :(得分:1)

代替这个。

while True:
            hint = float(driver.find_elements_by_xpath("//td[@class='col-prix']")[0].text.strip()[:-1].replace(",","."))
            if minPrice <= hint <= maxPrice: break
            driver.find_elements_by_xpath("//button")[0].click()
            driver.find_elements_by_xpath("//button")[0].click()
            sleep(1)

尝试以下代码。

while True:
price = float(driver.find_elements_by_xpath("//td[@class='col-prix']")[0].text.strip()[:-1].replace(",", "."))
print(price)
if a <= price <= b: break
element=WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH,"//button/span[text()='Tous les billets']")))
ActionChains(driver).move_to_element(element).perform()
driver.refresh()

请告诉我它是否有效。