如果在 python 上显示错误消息,如何跳过请求

How to skip a request if it shows an error message on python

我想创建一个脚本,使用 selenium 从网站上获取信息。

但是,如果它找不到信息并显示一条错误消息,它会跳过该请求并继续执行下一个请求。


from selenium import webdriver
import pandas as pd
import undetected_chromedriver as uc

list1 = [6019306,6049500,6051161,6022230,5776662,6151430]

for x in range(0, list1.count()):
    while True:
        try: 
            options = webdriver.ChromeOptions() 
            options.add_argument("start-maximized")
            driver = uc.Chrome(options=options)
            url = 'https://www.axie.tech/axie-pricing/'+str(list1[x])
            driver.get(url)
            driver.implicitly_wait(10)


            test = driver.find_element_by_xpath('//*[@id="root"]/div[1]/div[2]/div[2]/div/div/div[1]/div/div[1]/div[4]/div/div[3]/div/span').text
            test = float(test[1:])
            print(test)


            driver.close()
        except NoSuchElementException:
            'This Value doesnt exist'
            driver.close()

有点不清楚你到底想通过 test = float(test[1:]).

行做什么

然而,要从您需要诱导的网站列表中提取所需的文本 WebDriverWait for and you can use the following :

  • 代码块:

    options = webdriver.ChromeOptions()     
    options.add_argument("start-maximized")
    driver = uc.Chrome(options=options)
    list1 = [6019306, 6049500, 6051161, 6022230, 5776662, 6151430]
    for x in range(0, len(list1)):
        try:
            url = 'https://www.axie.tech/axie-pricing/'+str(list1[x])
            driver.get(url)
            print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[text()='Reasonable']//following::div[1]//span[contains(@class, 'MuiTypography-root')]"))).text)
        except TimeoutException:
            continue
    driver.quit()
    
  • 控制台输出:

    Ξ0.01
    Ξ0.012
    Ξ0.0162
    Ξ0.026
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException