是否有 Selenium 等到下载完成? [英] Is there a Selenium wait until download complete?
问题描述
我有一个程序使用 selenium 下载文件,然后使用 os.listdir
获取文件名.
I have a program that downloads a file using selenium and then gets the file name with os.listdir
.
我现在的问题是下载时间太长,而我的代码已经继续这个过程.如何在文件下载之前暂停代码?
My problem right now is that the download takes too long, and my code has moved on with the process. How can I pause the code until the file is downloaded?
是否有 selenium 等待下载完成,或者 selenium 将下载的文件名传递到一个变量中,我可以从 这里
Is there a selenium wait until download complete, or a way for selenium to pass the downloaded files name into a variable that i can plug into the answer from here
driver.find_element(By.XPATH, '//button[text()="Export to CSV"]').click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Download"]')))
driver.find_element(By.XPATH, '//button[text()="Download"]').click()
files=os.listdir(folderPath)#finds all files in folder
print(files)
推荐答案
你的问题的明确答案是否.Selenium 没有这样的方法来等待下载完成.
The clear answer of you question is No. Selenium don't have such method to wait until download get completed.
您可以编写自己的自定义方法,在一定时间间隔内连续检查下载目录中的下载文件名.
You can write your own custom method which check downloaded file name in download directory continuously in some time interval.
def is_file_downloaded(filename, timeout=60):
end_time = time.time() + timeout
while not os.path.exists(filename):
time.sleep(1)
if time.time() > end_time:
print("File not found within time")
return False
if os.path.exists(filename):
print("File found")
return True
在点击下载的代码行之后调用该方法.
Call that method just after code line which hits download.
driver.find_element(By.XPATH, '//button[text()="Download"]').click()
file_path = '/Users/narendra.rajput/Documents/30.docx'
if is_file_downloaded(file_path, 30):
print("yes")
else:
print("No")
这篇关于是否有 Selenium 等到下载完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!