Python`urllib2`:为什么在“urlopen”维基百科页面时会出现错误403?

问题描述 投票:52回答:6

当我试图从维基百科的某个页面尝试urlopen时,我有一个奇怪的错误。这是页面:

http://en.wikipedia.org/wiki/OpenCola_(drink)

这是shell会话:

>>> f = urllib2.urlopen('http://en.wikipedia.org/wiki/OpenCola_(drink)')
Traceback (most recent call last):
  File "C:\Program Files\Wing IDE 4.0\src\debug\tserver\_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "c:\Python26\Lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "c:\Python26\Lib\urllib2.py", line 397, in open
    response = meth(req, response)
  File "c:\Python26\Lib\urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "c:\Python26\Lib\urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "c:\Python26\Lib\urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "c:\Python26\Lib\urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

这发生在我不同大陆的两个不同系统上。有谁知道为什么会这样?

python http urllib2
6个回答
120
投票

Wikipedias stance is

数据检索:对于与批准的机器人任务没有直接关系的任何用途,Bots不得用于检索批量内容。这包括从其他网站动态加载页面,这可能导致网站被列入黑名单并被永久拒绝访问。如果您想下载批量内容或镜像项目,请下载或托管您自己的数据库副本。

这就是Python被阻止的原因。你应该download data dumps

无论如何,你可以在Python 2中阅读这样的页面:

req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) 
con = urllib2.urlopen( req )
print con.read()

或者在Python 3中:

import urllib
req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) 
con = urllib.request.urlopen( req )
print con.read()

10
投票

要调试它,您需要捕获该异常。

try:
    f = urllib2.urlopen('http://en.wikipedia.org/wiki/OpenCola_(drink)')
except urllib2.HTTPError, e:
    print e.fp.read()

当我打印生成的消息时,它包括以下内容

“英语

我们的服务器目前遇到技术问题。这可能是暂时的,应尽快解决。请在几分钟后再试一次。 “


5
投票

网站通常会通过检查是否由公认的用户代理访问来过滤访问。维基百科只是将您的脚本视为机器人并拒绝它。尝试欺骗浏览器。以下链接将为您提供一篇文章,向您展示如何。

http://wolfprojects.altervista.org/changeua.php


1
投票

一些网站将阻止从脚本访问,以通过阅读urllib发送的标题来避免对其服务器的“不必要”使用。我不知道也无法想象为什么维基百科会/会这样做,但你试过欺骗你的标题吗?


1
投票

正如Jochen Ritzel所说,维基百科阻止了机器人。

但是,如果机器人使用PHP api,它们将不会被阻止。要获得标题为“爱”的维基百科页面:

http://en.wikipedia.org/w/api.php?format=json&action=query&titles=love&prop=revisions&rvprop=content


0
投票

我使用php为此做了一个解决方法,我没有被我需要的网站阻止。

它可以像这样访问:

path='http://phillippowers.com/redirects/get.php? 
file=http://website_you_need_to_load.com'
req = urllib2.Request(path)
response = urllib2.urlopen(req)
vdata = response.read()

这将返回html代码给你

© www.soinside.com 2019 - 2024. All rights reserved.