使用selenium,我能够自动下载zip文件并将其保存到指定目录。然而,当我尝试解压缩文件时,我遇到了一个障碍,我似乎无法找到最近下载的文件。如果有帮助,这是与下载和解压缩过程相关的代码块:
# Click on Map Link
driver.find_element_by_css_selector("input.linksubmit[value=\"▸ Map\"]").click()
# Download Data
driver.find_element_by_xpath('//*[@id="buttons"]/a[4]/img').click()
# Locate recently downloaded file
path = 'C:/.../Download'
list = os.listdir(path)
time_sorted_list = sorted(list, key=os.path.getmtime)
file_name = time_sorted_list[len(time_sorted_list)-1]
具体来说,这是我的错误:
Traceback (most recent call last):
File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-89-3f1d00dac284>", line 3, in <module>
time_sorted_list = sorted(list, key=os.path.getmtime)
File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'grid-m1b566d31a87cba1379e113bb93fdb61d5be5b128.zip'
我尝试通过删除代码并在目录中放置另一个文件来对代码进行故障排除,然后我能够找到随机文件,但不能找到最近下载的文件。谁能告诉我这里发生了什么?
答案 0 :(得分:0)
首先,不要将list
用于变量名称。这使得list
构造函数无法在程序中的其他位置使用。其次,os.listdir
不返回该目录中文件的完整路径。如果你想要完整的路径,你可以做两件事:
您可以使用os.path.join
:
import zipfile
path = 'C:/.../Download'
file_list = [os.path.join(path, f) for f in os.listdir(path)]
time_sorted_list = sorted(file_list, key=os.path.getmtime)
file_name = time_sorted_list[-1]
myzip = zipfile.ZipFile(file_name)
for contained_file in myzip.namelist():
if all(n in contained_file.lower() for n in ('corn', 'irrigation', 'high', 'brazil')):
with myzip.open(contained_file) as f:
# save data to a CSV file
您还可以使用glob
模块中的glob
功能:
from glob import glob
import zipfile
path = 'C:/.../Download'
file_list = glob(path+"/*")
time_sorted_list = sorted(file_list, key=os.path.getmtime)
file_name = time_sorted_list[-1]
myzip = zipfile.ZipFile(file_name)
for contained_file in myzip.namelist():
if all(n in contained_file.lower() for n in ('corn', 'irrigation', 'high', 'brazil')):
with myzip.open(contained_file) as f:
# save data in a CSV file
要么应该工作。