在selenium中点击按钮下载判断文件是否下载成功可根据文件名或者文件大小判断且如果多个文件下载其中一个文件失败需要重试重试一定次数后记录失败的文件名且文件如果全部下载完成对每个文件修改名字对文件判断是否下载完成可以考虑文件名或者文件大小且修改文件名重复下载可能使用osrname考虑报错参考如下代码 修改def click_download_filesself urn el 文件点
下面是根据您提供的代码进行修改的示例:
import os
import re
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
def click_download_files(self, urn, el, retry_times=3):
"""文件点击下载"""
file_names = []
download_links = self.driver.find_elements(By.CSS_SELECTOR, el)
try:
for link in download_links:
file_title = link.get_attribute("title")
t_f_n = re.findall(REG, file_title)
if len(t_f_n) == 0:
QueryResult.update(UPDATE_INVOICES_SQL, (generate_utils.get_strtime(), urn))
continue
double_check = r'^\.'
tfn = re.findall(double_check, t_f_n[0].strip().strip())
if len(tfn) > 0:
QueryResult.update(UPDATE_INVOICES_SQL, (generate_utils.get_strtime(), urn))
continue
file_title = t_f_n[0].strip()
new_file_title = urn + "__" + t_f_n[0].strip() # 修改后的文件名
if link.is_enabled(): # 文件是否可点击下载
success = self.download_file(link, new_file_title)
if not success:
# Retry downloading the file
for _ in range(retry_times):
success = self.download_file(link, new_file_title)
if success:
break
if not success:
# Record the failed file name
file_names.append(new_file_title)
finally:
# Rename the downloaded files if all files have been successfully downloaded
if len(file_names) == 0:
for file in os.listdir():
if os.path.isfile(file):
# Modify the condition for determining if the file is downloaded successfully
if file.endswith(".pdf"):
os.rename(file, file.replace(".pdf", ".downloaded"))
elif os.path.getsize(file) > 0:
os.rename(file, file + ".downloaded")
else:
# Handle the failed files
pass # Add your code here to handle the failed files
def download_file(self, link, new_file_title):
"""Download the file"""
try:
ActionChains(self.driver).move_to_element(link).click().perform()
# Wait for the file to be downloaded (you can use WebDriverWait here)
return True # Modify the condition for determining if the file is downloaded successfully
except Exception as e:
return False
上述代码中,click_download_files函数会依次点击下载按钮,并通过download_file函数来实际进行文件下载操作。如果下载失败,会根据设置的重试次数进行重试,并记录失败的文件名。如果所有文件均下载成功,则会对每个文件进行重命名。您可以根据实际情况修改其中的判断条件和重试逻辑。请注意,上述代码中的文件下载成功判断条件仅作为示例,您需要根据实际情况修改
原文地址: https://www.cveoy.top/t/topic/h9nA 著作权归作者所有。请勿转载和采集!