我正在尝试使用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
任何人都可以帮我吗?
答案 0 :(得分:2)
zip一起列出:
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)
您正尝试使用字符串nameList
为x
编制索引,其中每个字符串都来自Namelist,即nameList["avg.exe"]
,这就是您的代码出错的原因。
如果您想索引,则需要enumerate:
for ind, x in enumerate(url):
urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ nameList[ind])
其中ind
是网址列表中每个元素的索引。
答案 1 :(得分:1)
您的错误在于您使用字符串索引列表,而不是整数,正如您在for循环中所述:
for x in url and nameList: #x is string here.
所以你需要用一个整数来索引你的nameList,如下所示:
for i, x in enumerate(url):
urllib.urlretrieve(x, "C:\\Users\\myName\\Desktop\\"+ nameList[i])