使用谷歌应用引擎在python中获取大量网址

时间:2014-10-28 13:56:41

标签: python google-app-engine python-2.7 webapp2

在我的RequestHandler子类中,我试图获取网址范围:

class GetStats(webapp2.RequestHandler):
    def post(self): 

    lastpage = 50   
    for page in range(1, lastpage):
        tmpurl = url + str(page)
        response = urllib2.urlopen(tmpurl, timeout=5)
        html = response.read()
        # some parsing html
        heap.append(result_of_parsing)  

    self.response.write(heap)

但是它适用于~30个网址(页面加载的时间很长但是很有效)。 如果超过30,我收到错误:

错误:服务器错误

服务器遇到错误,无法完成您的请求。

请在30秒后重试。

有没有办法获取很多网址?可能更优或更好? 最多几百页?

更新

我使用BeautifulSoup来解析每一页。我在gae日志中找到了这个追溯:

Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
  File "/base/data/home/apps/s~gae/1.379703839015039430/main.py", line 68, in post
heap = get_times(tmp_url, 160)
  File "/base/data/home/apps/s~gae/1.379703839015039430/main.py", line 106, in get_times
soup = BeautifulSoup(html)
  File "libs/bs4/__init__.py", line 168, in __init__
self._feed()
  File "libs/bs4/__init__.py", line 181, in _feed
self.builder.feed(self.markup)
  File "libs/bs4/builder/_htmlparser.py", line 56, in feed
super(HTMLParserTreeBuilder, self).feed(markup)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/HTMLParser.py", line 114, in feed
self.goahead(0)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/HTMLParser.py", line 155, in goahead
startswith = rawdata.startswith
 DeadlineExceededError

2 个答案:

答案 0 :(得分:5)

它失败了,因为你只有60秒的时间才能向用户返回一个回复,我猜它会花费更长的时间。

您需要使用此功能:https://cloud.google.com/appengine/articles/deferred

创建一个有10分钟超时的任务。然后,您可以立即返回给用户,他们可以选择"稍后通过另一个处理程序(您创建)的结果。如果收集所有网址需要的时间超过10分钟,您就必须将其拆分为更多任务。

请参阅:https://cloud.google.com/appengine/articles/deadlineexceedederrors

明白为什么你不能超过60秒。

答案 1 :(得分:0)

编辑: 可能来自Appengine配额和限制。 对不起,上一个回答:

因为这看起来像是对服务器的保护,以避免ddos或从一个客户端报废。你有几个选择:

  • 在继续之前等待一定数量的查询。

  • 向具有不同IP地址并将信息发送回主脚本的多个客户发出请求(为此租用不同的服务器可能代价高昂。)。

  • 您还可以观看网站是否为api,以便访问您需要的数据。

如果他确定您的请求不合适,您也应该小心,因为所有者可以阻止/将您的IP列入黑名单。