2014-07-20 6 views
1

urllib2를 사용하여 URL을 요청하고 내용을 읽었지만 불행히도 일부 URL에서는 작동하지 않습니다. 이 명령 보면 :python urllib2가 특정 URL을 가져올 수 없습니다.

#No problem with this URL 
urllib2.urlopen('http://www.huffingtonpost.com/2014/07/19/todd-akin-slavery_n_5602083.html') 
#This one produced error 
urllib2.urlopen('http://www.foxnews.com/us/2014/07/19/cartels-suspected-as-high-caliber-gunfire-sends-border-patrol-scrambling-on-rio/') 

두 번째 URL은 다음과 같이 생산 및 오류 :

이 함께 문제가 무엇
Traceback (most recent call last): 
    File "D:/Developer Center/Republishan/republishan2/republishan2/test.py", line 306, in <module> 
    urllib2.urlopen('http://www.foxnews.com/us/2014/07/19/cartels-suspected-as-high-caliber-gunfire-sends-border-patrol-scrambling-on-rio/') 
    File "C:\Python27\lib\urllib2.py", line 127, in urlopen 
    return _opener.open(url, data, timeout) 
    File "C:\Python27\lib\urllib2.py", line 410, in open 
    response = meth(req, response) 
    File "C:\Python27\lib\urllib2.py", line 523, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "C:\Python27\lib\urllib2.py", line 448, in error 
    return self._call_chain(*args) 
    File "C:\Python27\lib\urllib2.py", line 382, in _call_chain 
    result = func(*args) 
    File "C:\Python27\lib\urllib2.py", line 531, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 404: Not Found 

?

+1

이 답변은 urllib2를 사용하고 사용자 에이전트를 변경하여 제공 한 url과 함께 작동합니다. http://stackoverflow.com/a/5196160/2679935 – julienc

답변

6

나는 사이트가 User-Agent 및 urllib가 기본적으로 설정하지 않는 다른 헤더를 확인한다고 생각합니다.

사용자 에이전트를 수동으로 설정할 수 있습니다.

요청 라이브러리는 자동으로 사용자 에이전트를 설정합니다.

그러나 user-agent 요청이 일부 사이트에서 차단 될 수 있음을 기억하십시오.

시도해보십시오. 이것은 나를 위해 일하고있다. 먼저 요청 모듈을 설치해야합니다!

pip install requests 

그런 다음

import requests 

r = requests.get("http://www.foxnews.com/us/2014/07/19/cartels-suspected-as-high-caliber-gunfire-sends-border-patrol-scrambling-on-rio/") 

print r.text 

URLLIB 열심히 그리고 당신은 더 많은 코딩했습니다. 요청은 더 간단하고 코드가 아름답다는 Python 철학에 더 가깝습니다!

관련 문제