使用urllib下载时从数组中提取文件名

2024-04-24 08:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用用于python的urllib库从存储在数组中的url中提取各种工具。当我选择将它们保存到一个位置时,我希望以单独数组中的一个条目命名每个文件。每次我试着运行我在这里写的代码时:

import urllib

url = ["http://dw.cbsi.com/redir?ttag=restart_download_click&ptid=3001&pagetype=product_pdl&astid=2&edid=3&tag=link&siteid=4&destUrl=&onid=2239&oid=3001-2239_4-10320142&rsid=cbsidownloadcomsite&sl=en&sc=us&topicguid=security%2Fantivirus&topicbrcrm=&pid=14314872&mfgid=10044820&merid=10044820&ctype=dm&cval=NONE&devicetype=desktop&pguid=4ca3cb3823b670cd4386478c&viewguid=V4afV1BQaWxD1Ku2AKu@IeHzq6uWztjV6P2F&destUrl=http%3A%2F%2Fsoftware-files-a.cnet.com%2Fs%2Fsoftware%2F14%2F31%2F48%2F72%2Favg_free_stb_all_5961p1_177.exe%3Ftoken%3D1433990253_8690d8cb94b227464de5d6e1d59d78b4%26fileName%3Davg_free_stb_all_5961p1_177.exe","http://download.piriform.com/ccsetup506.exe"]
nameList = ["avg.exe","ccleaner.exe"]
for x in url and nameList:
    urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ nameList[x])

我收到错误

Traceback (most recent call last):
  File "P:\PythonProjects\programDownloader.py", line 6, in <module>
    urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ nameList[x])
TypeError: list indices must be integers, not str

有人能帮我吗?你知道吗


Tags: incomfreehttpurldownload数组all
2条回答

zip如果要匹配for循环中解包的每个列表中的相应元素,请将这些列表放在一起:

url = ["http://dw.cbsi.com/redir?ttag=restart_download_click&ptid=3001&pagetype=product_pdl&astid=2&edid=3&tag=link&siteid=4&destUrl=&onid=2239&oid=3001-2239_4-10320142&rsid=cbsidownloadcomsite&sl=en&sc=us&topicguid=security%2Fantivirus&topicbrcrm=&pid=14314872&mfgid=10044820&merid=10044820&ctype=dm&cval=NONE&devicetype=desktop&pguid=4ca3cb3823b670cd4386478c&viewguid=V4afV1BQaWxD1Ku2AKu@IeHzq6uWztjV6P2F&destUrl=http%3A%2F%2Fsoftware-files-a.cnet.com%2Fs%2Fsoftware%2F14%2F31%2F48%2F72%2Favg_free_stb_all_5961p1_177.exe%3Ftoken%3D1433990253_8690d8cb94b227464de5d6e1d59d78b4%26fileName%3Davg_free_stb_all_5961p1_177.exe","http://download.piriform.com/ccsetup506.exe"]
nameList = ["avg.exe","ccleaner.exe"]
for x, name in zip(url,nameList):
    urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ name)

您正试图用字符串x索引nameList,该字符串是Namelist中的每个字符串,即nameList["avg.exe"],这就是代码出错的原因。你知道吗

如果要索引,则需要enumerate

for ind, x in enumerate(url):
    urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ nameList[ind])

其中ind是url列表中每个元素的索引。你知道吗

您的错误是使用字符串而不是整数为列表编制索引,正如您在for循环中所述:

for x in url and nameList: #x is string here.

所以你需要用一个整数来索引你的名字列表,如下所示:

for i, x in enumerate(url):
    urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ nameList[i])

相关问题 更多 >