Selenium的例外:如何继续脚本?

问题描述 投票:-1回答:2

我不断遇到代码问题。虽然我终于能够打开网页,点击一个按钮,然后下载excel文件,我遇到了一个错误:找不到这样的元素。

我有一个URL列表,Selenium很好地通过列表,直到它遇到一个具有不同配置的url并且找不到'element'。我想让python跳过那个url并转到下一个url。我将来可以手动回到'broken-url'。

这是我的代码:

with open('C:/Users/ovtch/PyScript/source.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        urlList.append(row['URL'])

driver = webdriver.Chrome(executable_path='chromedriver.exe')


def downloadCSV():
    count=1
    for url in urlList:

        driver.get(url)
        # Page Scraping Prepare
        time.sleep(1)
        driver.find_element_by_xpath('my path').click()
        time.sleep(1)
        driver.find_element_by_xpath('my path').click()
        count+=1

"""Show starting time"""
print("Start project time")
print(datetime.datetime.now().time())

downloadCSV()

"""Show end time"""
print("End project time")
print("Success")
time.sleep(8)
#driver.quit()
selenium exception download element
2个回答
0
投票

试试这个,将find_element_by_ *方法包装在异常块中并相应地处理异常

from selenium.common.exceptions import NoSuchElementException

def downloadCSV():
    count=1
    for url in urlList:
    try:
        driver.get(url)
        # Page Scraping Prepare
        time.sleep(1)
        driver.find_element_by_xpath('my path').click()
        time.sleep(1)
        driver.find_element_by_xpath('my path').click()
        count+=1
     except NoSuchElementException:
         pass # or handle the error

0
投票

您可以使用try / catch并忽略错误并继续循环:

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

#your code....

    for url in urlList:
        try:
            driver.get(url)
            # Page Scraping Prepare
            # Wait until your button is clickable and click
            WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "my path"))).click()
        except:
            continue
© www.soinside.com 2019 - 2024. All rights reserved.