【问题标题】:Open URLS from list and write data从列表中打开 URL 并写入数据
【发布时间】:2014-07-07 14:35:05
【问题描述】:

我正在编写一个创建多个 URL 的代码,这些 URL 又存储在一个列表中。 下一步是,打开每个 URL,下载数据(只是文本,格式为 XML 或 JSON)并保存下载的数据。

感谢这里的在线社区,我的代码运行良好。它停留在打开 URL 并下载数据的地方。我希望 url.request 使用我创建的 url 遍历列表并分别调用每个 url,打开它,显示它并继续下一个。但它只执行循环来创建 url,但什么也没有。没有反馈,什么都没有。

import urllib.request

.... some calculations for llong and llat ....


#create the URLs and store in list
urls = []
for lat,long,lat1,long1 in (zip(llat, llong,llat[1:],llong[1:])):
    for pages in range (1,17):
        print ("https://api.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=5.b&nojsoncallback=1&page={}&per_page=250&bbox={},{},{},{}&accuracy=1&has_geo=1&extras=geo,tags,views,description".format(pages,long,lat,long1,lat1))
print (urls)


#accessing the website 
data = []
for amounts in urls:
    response = urllib.request.urlopen(urls)
    flickrapi = data.read()
    data.append(+flickrapi)
    data.close()
    print (data)

我做错了什么?

下一步是下载数据并将其保存到文件或其他位置以供进一步处理。 由于我将收到大量数据,就像很多很多一样,我不确定存储它以使用 R(或者可能是 Python?- 需要对其进行一些统计工作)对其进行处理的最佳方法是什么。有什么建议吗?

【问题讨论】:

    标签: python url screen-scraping bigdata urllib


    【解决方案1】:

    您没有将生成的 url 附加到 url 列表中,而是在打印它们:

    print ("https://api.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=5.b&nojsoncallback=1&page={}&per_page=250&bbox={},{},{},{}&accuracy=1&has_geo=1&extras=geo,tags,views,description".format(pages,long,lat,long1,lat1))
    

    应该是:

    urls.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=5.b&nojsoncallback=1&page={}&per_page=250&bbox={},{},{},{}&accuracy=1&has_geo=1&extras=geo,tags,views,description".format(pages,long,lat,long1,lat1))
    

    然后你就可以按计划遍历 url。

    但是你会在下面一行遇到错误:

    response = urllib.request.urlopen(urls)
    

    在这里,您将整个网址集输入urlopen,您应该从您命名为amounts 的网址中传入一个网址,如下所示:

    response = urllib.request.urlopen(amounts)
    

    【讨论】:

    • 这样做,这就是我得到的反馈Traceback (most recent call last): File "/Users/christoph/Desktop/test.py", line 54, in <module> response = urllib.request.urlopen(urls) File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 156, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 460, in open req.timeout = timeout AttributeError: 'list' object has no attribute 'timeout'
    • 啊,太棒了!下一步是下载数据。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    相关资源
    最近更新 更多