gpt4 book ai didi

python - 维基百科是否允许通过 Google App Engine 获取 URL?

转载 作者:太空狗 更新时间:2023-10-30 02:34:35 25 4
gpt4 key购买 nike

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

代码片段(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 默认用户代理被维基百科禁止,它会导致 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

关于python - 维基百科是否允许通过 Google App Engine 获取 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7543571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com