我正在编写一个Python web应用程序,其中我计划利用维基百科。当尝试一些网址抓取代码时,我能够同时抓取谷歌和脸书(通过谷歌应用引擎服务),但当我试图抓取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))发布于 2011-09-26 15:35:18
维基百科禁止使用urllib2默认用户代理,它会导致403HTTP响应。
您应该使用如下内容修改您的应用程序用户代理:
#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
发布于 2011-09-27 08:40:51
您可以将用户代理设置为您想要的任何字符串;App Engine将对其进行修改,以附加字符串AppEngine-Google; (+http://code.google.com/appengine; appid: yourapp)。在urllib2中,您可以像这样设置用户代理头:
req = urllib2.Request("http://en.wikipedia.org/", headers={"User-Agent": "Foo"})
response = urllib2.urlopen(req)https://stackoverflow.com/questions/7543571
复制相似问题