2010-07-26 5 views
42

위키피디아의 특정 페이지 urlopen을 시도 할 때 이상한 버그가 있습니다.파이썬의`urllib2` : 위키 피 디아 페이지를`urlopen '할 때 왜 403 오류가 발생합니까?

>>> 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 

이 다른 대륙에서 두 개의 서로 다른 시스템에 내게 일어난 :

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

이 쉘 세션 :이 페이지입니다. 왜 이런 일이 일어나는 지 아는 사람이 있습니까?

+0

당신은 그 괄호를 URL 인코딩 할 수 있습니다 당신에게 HTML 코드를 반환합니다. 그것은 403에 대해 도움이되지는 않지만. – Thomas

+0

wikimedia API의 링크를 사용할 수도 있습니다. https://www.mediawiki.org/wiki/API:Main_page – chackerian

답변

101

Wikipedias stance is 포함

파이썬이 차단 된 이유

Data retrieval: Bots may not be used to retrieve bulk content for any use not directly related to an approved bot task. This includes dynamically loading pages from another website, which may result in the website being blacklisted and permanently denied access. If you would like to download bulk content or mirror a project, please do so by downloading or hosting your own copy of our database.

. 당신은 download data dumps입니다.

어쨌든, 당신은 파이썬이이 같은 페이지를 읽을 수 있습니다

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

또는 파이썬 3을 :

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

"그렇기 때문에 파이썬이 차단되었습니다." 이 문장은 무엇을 의미하지 않습니까? 그러나 나는 'User-Agent'목록을 작성하고 무작위로 URL 중 하나를 선택하여 웹 사이트에서 "urllib2.URLError : "또는 내 IP를 차단했습니다. 그들의 웹 사이트 방문에서. 아이디어를 더 줄 수 있습니까? 많은 감사. – MaiTiano

+0

그들이 HEAD 요청을 차단한다는 것은 완전히 우스꽝 스럽다. 사용자가 게시 한 모든 링크의 유효성을 검사합니다. – ThiefMaster

+0

이 접근법은 나에게 403을 반환하는 HTTPS 페이지에서도 작동한다. 왜 urllib2.urlopen()이 403을 얻는 반면, 그것이 작동 하는가? – Pyderman

1

일부 웹 사이트는 urllib가 보내는 헤더를 읽음으로써 서버의 '불필요한'사용을 피하기 위해 스크립트에서 액세스를 차단합니다. 왜 위키 피 디아가 그렇게하는지/상상할 수는 없지만 헤더를 스푸핑 해 보았습니까?

+2

http://meta.wikimedia.org/wiki/Bot_policy –

5

종종 웹 사이트는 인식 된 사용자 에이전트가 액세스하고 있는지 확인하여 액세스를 필터링합니다. Wikipedia는 스크립트를 봇으로 간주하고 거부합니다. 브라우저로 스푸핑을 시도하십시오. 다음 링크는 당신에게 기사를 보여줍니다.

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

9

이를 디버깅하려면, 당신은 함정에 그 예외를해야합니다. 나는 결과 메시지를 인쇄 할 때

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

, 그것은 다음과 같은

"English

Our servers are currently experiencing a technical problem. This is probably temporary and should be fixed soon. Please try again in a few minutes. "

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() 

관련 문제