【问题标题】:Iterate through list to download items in python遍历列表以在python中下载项目
【发布时间】:2017-07-31 20:06:01
【问题描述】:

我之前发布了this 的问题,寻求有关python 脚本的帮助,但没有得到太多反馈,这没关系!因为我自己弄清楚了如何处理其中的大部分内容,但我遇到了一些麻烦。

我的脚本目前是这样的:

param1 = 
param2 = 
param3 = 

requestURL = "http://examplewebpage.com/live2/?target=param1&query=param2&other=param3"

html_content = urllib2.urlopen(requestURL).read()

matches = re.findall('<URL>(.*?)</URL>', html_content);

myList=[matches]

i = 0
while i < len(myList):
    testfile = urllib.URLopener()
    testfile.retrieve(myList[i], "/Users/example/file/location/newtest")
    i += 1

这成功地从网页中检索所有 URL,但我找不到继续下载过程的方法。我目前收到以下错误:'list' object has no attribute 'strip'

谁能想到更好的方法来做到这一点?或者除了列表之外,我应该使用其他数据类型吗?

【问题讨论】:

    标签: python url download


    【解决方案1】:

    我认为主要问题是myList=[matches] 创建了一个新列表,其中只有一个元素。该单个元素本身就是一个匹配列表。

    因此,当您稍后在循环中访问 myList[0] 时,它实际上是一个列表。因此出现错误。

    假设你的其余代码是正确的,我认为如果你切换到myList=matches,事情可能会奏效,但这里有一个使用更清晰的变量名和for循环的版本:

    requestURL = "http://examplewebpage.com/live2/?target=param1&query=param2&other=param3"
    
    html_content = urllib2.urlopen(requestURL).read()
    
    matches = re.findall('<URL>(.*?)</URL>', html_content);
    
    for url in matches:
        testfile = urllib.URLopener()
        testfile.retrieve(url, "/Users/example/file/location/newtest")
    

    编辑

    当然,每个页面都会写入同一个文件,除非URLopener.retrieve 执行自动重命名文件之类的操作?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多