2012-08-05 46 views
1

可能重複:
Fetch a Wikipedia article with Python爲什麼我不能使用urllib2.urlopen作爲維基百科網站?

>>> print urllib2.urlopen('http://zh.wikipedia.org/wiki/%E6%AF%9B%E6%B3%BD%E4%B8%9C').read() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open 
    response = meth(req, response) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error 
    return self._call_chain(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain 
    result = func(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 403: Forbidden 
+0

可能嗎?定。 – 2012-08-05 05:58:35

+0

查看他們的(robots.txt)[http://zh.wikipedia.org/robots.txt]頁面,查看您使用的bot是否被禁止 – elssar 2012-08-05 06:06:42

回答

1

嘗試的cURLwget下載頁面。
如果你不能,那麼你可能有網絡問題。
如果可以,維基百科可能會阻止某些用戶代理。在這種情況下,使用urllib2的add_header來定義自定義用戶代理(模仿瀏覽器請求)。

+0

不需要模仿瀏覽器請求,只需使用自定義用戶代理。我在使用用戶代理「elssar-at-elssar-laptop」時得到了結果。 – elssar 2012-08-05 06:49:31

6

您需要像您一樣提供用戶代理else you'll get a 403

在維基百科維基媒體,如果你不提供一個User-Agent頭,或者你 提供一個空或一般,您的請求將失敗與HTTP 403錯誤。 See our User-Agent policy。其他MediaWiki安裝 可能有類似的政策。

所以,只需將一個用戶代理添加到您的代碼,它應該工作正常。