Selenium Python 如何每隔 10 秒运行一次 XPath 错误处理异常?

问题描述 投票:0回答:1

我是新人,我正在做的项目有一个问题。我试图让我的代码,特别是错误处理部分每隔 10 可能 30 秒运行一次,以查看是否仍然检测到 xpath 以及是否检测到它,我希望它什么也不做,但如果没有检测到它,我希望它运行异常,尽管我在弄清楚如何做到这一点上遇到问题,任何人都可以帮忙吗?

我的代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
import schedule
import time
import pyautogui


def code():
    options = Options()
    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                              options=options)

    driver.get("example")
    driver.set_window_position(0, 0)
    driver.set_window_size(750, 512)

    try:
        driver.find_element(By.XPATH, "/html/body/div/div/div/div/div[2]/div/div/div[2]/div[2]/div[1]/span/button/span")
        print("success")
    except NoSuchElementException:  # spelling error making this code not work as expected
        pyautogui.moveTo(89, 56)
        time.sleep(1)
        pyautogui.click()
        print("Error but moved to refresh")
        pass

当前代码工作没有错误,我只需要它以 10 - 30 秒的间隔运行,但只是错误处理部分,我需要它来检查并查看 XPath 是否仍然存在。

python selenium-webdriver error-handling
1个回答
0
投票

我确信这种类型的命令会解决您的问题,尽管我仅使用它来检测页面中何时存在某些内容或何时可以选择它(而不是相反)。创建“驱动程序”后即可使用它:

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

wait = WebDriverWait(driver, 20)
# Below line of code will click on Accept cookies button
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Reject All']"))).click()
wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='c12-container']")))

By 有更多选项(CLASS、NAME 等)。探索 WebDriverWait,因为当不再检测到 XPATH 时,您肯定可以找到要触发的东西。 我希望它有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.