Python 即使我';我使用的是一种尝试和例外的方法

Python 即使我';我使用的是一种尝试和例外的方法,python,selenium,selenium-chromedriver,Python,Selenium,Selenium Chromedriver,我想使用selenium从网站下载数百万个excel文件。我当前的代码试图处理ElementNotVisibleException的问题,但我的“try和except”方法似乎有缺陷 我已经尝试实现了一个try and except解决方案,如果出现错误消息,我会指示Selenium等待直到“按钮”出现 我希望代码下载所有文件(如果有),但会出现ElementNotVisibleException或ElementClickInterceptedException。在对元素执行任何操作之前,请首先

我想使用selenium从网站下载数百万个excel文件。我当前的代码试图处理ElementNotVisibleException的问题,但我的“try和except”方法似乎有缺陷

我已经尝试实现了一个try and except解决方案,如果出现错误消息,我会指示Selenium等待直到“按钮”出现


我希望代码下载所有文件(如果有),但会出现ElementNotVisibleException或ElementClickInterceptedException。在对元素执行任何操作之前,请首先检查它是否可见
import os
import time
import csv
from tqdm import tqdm
import pandas as pd
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import ElementClickInterceptedException

working_directory = r"xx"
os.chdir(working_directory)
options = webdriver.ChromeOptions() 

prefs = {
        "download.default_directory": r"xx",
       "download.prompt_for_download": False,
       "download.directory_upgrade": True}

options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(r"C:xxx\chromedriver.exe", options = options) 

driver.get("website")

# Login
driver.find_element_by_class_name("smallLoginBox").click()
driver.implicitly_wait(1)
time.sleep(2) 
driver.find_element_by_id('loginFormUC_loginEmailTextBox').send_keys('EMAIL')
driver.find_element_by_id('loginFormUC_loginPasswordTextBox').send_keys('PASWORD')
driver.find_element_by_xpath("//input[@value='Logg inn']").click()

# Get a custom list of firms
bedrifter  = []

with open("./listwithIDs.csv") as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        bedrifter.append(row[0])

# THE LOOP

for ID in tqdm(bedrifter_gjenstår):
    driver.get("website" + ID)
    source = driver.page_source

    if not "Ingen data" in source: # make sure there is an excel file. If not, loop continues to next ID.
        # first click on button "download excel"
        try:
            driver.find_element_by_id("exportExcel").click()
        except ElementNotVisibleException:
            WebDriverWait(driver, 120).until(
                    EC.presence_of_element_located((By.ID, "exportExcel")))
            driver.find_element_by_id("exportExcel").click()
        except ElementClickInterceptedException:
            WebDriverWait(driver, 120).until(
                    EC.presence_of_element_located((By.ID, "exportExcel")))
            driver.find_element_by_id("exportExcel").click()

        # second click, choosing what format the excel file should be in
        try:
            driver.find_element_by_id("mainContentPlaceHolder_mainContentPlaceHolder_mainContentPlaceHolder_AccountingNumberTableUc_excelLinkButton").click()
        except ElementNotVisibleException:
            WebDriverWait(driver, 120).until(
                    EC.presence_of_element_located((By.ID, "mainContentPlaceHolder_mainContentPlaceHolder_mainContentPlaceHolder_AccountingNumberTableUc_excelLinkButton")))
            driver.find_element_by_id("mainContentPlaceHolder_mainContentPlaceHolder_mainContentPlaceHolder_AccountingNumberTableUc_excelLinkButton").click()

# code to switch between windows to remove download window and continue the code
        try: 
            window_export = driver.window_handles[1]
        except IndexError:
            time.sleep(3)
            print("sleep")
            window_export = driver.window_handles[1]

        try:
            window_main = driver.window_handles[0]
        except IndexError:
            time.sleep(3)
            print("sleep")
            window_main = driver.window_handles[0]

        driver.switch_to.window(window_export)
        driver.close()
        driver.switch_to.window(window_main)

下面是示例代码:

wait = WebDriverWait(self.browser, 15)
wait.until(EC.visibility_of_element_located(("element_path")))
driver.find_element_by_xpath("element_path").click()

要确保元素不仅存在且可见,而且可单击作为等待条件检查可剪裁性:

element = WebDriverWait(driver, 120).until(EC.element_to_be_clickable((By.ID, "exportExcel"))).click()

可以找到有关Python等待的更多信息。

您可能会遇到这些异常,因为它们发生在
except
子句中,而不是
try
中。请查看回溯以确定哪一行引发了异常。这应该告诉你问题出在哪里。
此外,如果您想等待元素可见,则应该使用位于的元素的可见性,而不是位于的元素的存在性。要记住的一件事是驱动程序。find\u element\u by()期望您的元素在点击这行代码时准备就绪。它使用了“查找”这个词,但更像是“嘿,司机,我保证它在那里,看一看。”这似乎是可行的。当我尝试在两个chrome窗口之间切换时,另一个问题似乎是出现了错误“索引超出范围”。这特别发生在
try:window\u export=driver.window\u句柄[1]除索引器外:time.sleep(3)print(“sleep”)window\u export=driver.window\u handles[1]
我是否可以使用类似的等待功能让selenium知道“等待两个窗口加载完毕,然后执行在两个窗口之间切换的操作?”“?存在
预期的\u条件。将要出现的\u窗口数
预期的\u条件。新的\u窗口已打开
或其他。