【发布时间】:2021-05-08 10:15:54
【问题描述】:
我正在尝试使用 selenium 下载和重命名文件(每页大约 60 个),但遇到了困难。
这是我尝试过的:
1.尝试使用supputuri提供的解决方案,通过chrome://downloads下载管理器,我使用了提供的代码但遇到了2个问题:打开的选项卡没有正确关闭(我可以修复),大多数重要的是,尽管我可以在我的下载目录中找到下载的文件,但提供的帮助函数会一直返回“无”作为文件名。这种方法可以工作,但需要在我不知道的 chrome 控制台命令部分进行一些修改。
# method to get the downloaded file name
def getDownLoadedFileName(waitTime):
driver.execute_script("window.open()")
# switch to new tab
driver.switch_to.window(driver.window_handles[-1])
# navigate to chrome downloads
driver.get('chrome://downloads')
# define the endTime
endTime = time.time()+waitTime
while True:
try:
# get downloaded percentage
downloadPercentage = driver.execute_script(
"return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")
# check if downloadPercentage is 100 (otherwise the script will keep waiting)
if downloadPercentage == 100:
# return the file name once the download is completed
return driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text")
except:
pass
time.sleep(1)
if time.time() > endTime:
break
Selenium give file name when downloading
- 我看到的第二种方法是 Red 从下面的帖子中提供的。我想因为我一次下载一个文件,我总是可以找到最新的文件,然后在下载完成后更改文件名并重复这个过程。对于这种方法,我有以下问题:一旦我抓住了文件对象,我似乎找不到获取文件名的方法,我检查了 file 对象的 python 方法,但它没有一种返回文件名的方法。
import os
import time
def latest_download_file(num_file,path):
os.chdir(path)
while True:
files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime)
#wait for file to be finish download
if len(files) < num_file:
time.sleep(1)
print('waiting for download to be initiated')
else:
newest = files[-1]
if ".crdownload" in newest:
time.sleep(1)
print('waiting for download to complete')
else:
return newest
python selenium, find out when a download has completed?
如果您有任何建议,请告诉我。谢谢。
【问题讨论】:
-
您不使用请求进行实际下载的任何原因?
-
@goalie1998 我没有发布下载代码,因为它只有几行,并且可以执行我想要它执行的操作。人们说 selenium 无法控制下载文件的名称,必须在操作系统级别完成。
-
你可以分享使用的网址吗?
-
link 每个候选人都有一个下载按钮(需要登录)。
-
检查目录时可能存在时间问题。最好的方法是获取从服务器返回的响应标头。这将包括文件名。然后,您可以专门检查该文件是否出现(首先使用 .crdownload ...)所以可能会触发该文件的 ajax 请求...然后您可以获得响应标头或 xhr 对象。 (jQuery 中的 jqxhr)
标签: python selenium web-scraping