【问题标题】:Does Wikipedia allow URL fetching via Google App Engine?Wikipedia 是否允许通过 Google App Engine 获取 URL?
【发布时间】:2011-11-24 12:10:20
【问题描述】:

我正在编写一个 Python 网络应用程序,并计划在其中利用 Wikipedia。在尝试一些 URL Fetching 代码时,我能够同时获取 Google 和 Facebook(通过 Google App Engine 服务),但是当我尝试获取 wikipedia.org 时,我收到了一个异常。谁能确认维基百科不接受这些类型的页面请求?维基百科如何区分我和用户?

代码 sn-p(它是 Python!):

    import os
import urllib2
from google.appengine.ext.webapp import template


class MainHandler(webapp.RequestHandler):
    def get(self):
        url = "http://wikipedia.org"
        try:
          result = urllib2.urlopen(url)
        except urllib2.URLError, e:
          result = 'ahh the sky is falling'
        template_values= {
            'test':result,
        }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

【问题讨论】:

  • 抛出了什么异常?我假设它是 urllib2.URLError 的子类,它可能会让您更好地了解问题。
  • 你不能使用urlfetch api吗?它似乎对我有用。 AFAIK urllib2 默认用户代理被维基百科禁止,您无法在 gae 上更改它。
  • “一个例外”是非常无用的。向我们展示堆栈跟踪!
  • @systempuntoout 您可以更改用户代理,但不能从中删除 App ID。
  • @systempuntoout 是的,你可以。我刚刚使用 shell.appspot.com 对其进行了测试,正如预期的那样,它将AppEngine-Google; (+http://code.google.com/appengine; appid: shell) 添加到您指定的任何用户代理标头的末尾。

标签: python http google-app-engine url web-applications


【解决方案1】:

urllib2 默认用户代理被维基百科禁止,它会导致 403 HTTP 响应。
您应该使用以下内容修改您的应用程序用户代理:

#Option 1
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'MyUserAgent')]
res= opener.open('http://whatsmyuseragent.com/')
page = res.read()

#Option 2
import urllib2
req = urllib2.Request('http://whatsmyuseragent.com/')
req.add_header('User-agent', 'MyUserAgent')
urllib2.urlopen(req)

#Option 3
req = urllib2.Request("http://whatsmyuseragent.com/", 
                       headers={"User-agent": "MyUserAgent"})
urllib2.urlopen(req)

奖励链接:
高层Wikipedia Python Clients http://www.mediawiki.org/wiki/API:Client_code#Python

【讨论】:

  • 那些 sn-ps 在 shell.appspot.com 上失败是因为 shell 中的错误,而不是因为 urllib 中的错误:如果您在一个命令中在 shell 上创建一个对象,然后尝试修改它在另一种情况下,更改不会持续存在。将上面的代码放在一个函数中并执行它,它会正常工作。
  • 非常好的答案!我真的印象深刻,解释+链接也很有帮助。
【解决方案2】:

您可以将您的用户代理设置为您希望的任何字符串;它将被 App Engine 修改为附加字符串 AppEngine-Google; (+http://code.google.com/appengine; appid: yourapp)。在 urllib2 中,您可以像这样设置 user-agent 标头:

req = urllib2.Request("http://en.wikipedia.org/", headers={"User-Agent": "Foo"})
response = urllib2.urlopen(req)

【讨论】:

    猜你喜欢
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2014-05-21
    • 1970-01-01
    • 2016-09-26
    • 2010-11-20
    相关资源
    最近更新 更多