我想使用 selenium 從網(wǎng)站下載數(shù)百萬(wàn)個(gè) excel 文件。我當(dāng)前的代碼嘗試處理 ElementNotVisibleException 的問(wèn)題,但我的“嘗試和例外”方法似乎不足。我試圖實(shí)施一個(gè)嘗試和例外解決方案,如果出現(xiàn)錯(cuò)誤消息,我已指示 Selenium 等到“按鈕”出現(xiàn)。import osimport timeimport csvfrom tqdm import tqdmimport pandas as pdfrom selenium import webdriverfrom selenium.common.exceptions import NoSuchElementExceptionfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import ElementNotVisibleExceptionfrom selenium.common.exceptions import ElementClickInterceptedExceptionworking_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")# Logindriver.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 firmsbedrifter = []with open("./listwithIDs.csv") as csvDataFile: csvReader = csv.reader(csvDataFile) for row in csvReader: bedrifter.append(row[0])我希望代碼能夠下載所有文件(如果有),但會(huì)出現(xiàn) ElementNotVisibleException 或 ElementClickInterceptedException。
3 回答

慕勒3428872
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可能會(huì)遇到這些異常,因?yàn)樗鼈儼l(fā)生在except
子句中,而不是在try
. 請(qǐng)查看回溯以確定哪一行引發(fā)了異常。這應(yīng)該告訴你問(wèn)題出在哪里。此外,如果您想等待元素可見,您應(yīng)該使用visibility_of_element_located
而不是presence_of_element_located

紫衣仙女
TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
在對(duì)元素執(zhí)行任何操作之前,首先檢查它是否可見這是示例代碼:
wait = WebDriverWait(self.browser, 15)
wait.until(EC.visibility_of_element_located(("element_path")))
driver.find_element_by_xpath("element_path").click()
添加回答
舉報(bào)
0/150
提交
取消