2008-10-14 9 views
11

나는 테스트하고있는 간단한 웹 사이트가 있습니다. 로컬 호스트에서 실행 중이며 웹 브라우저에서 액세스 할 수 있습니다. 색인 페이지는 단순히 "실행 중"이라는 단어입니다. urllib.urlopen은 페이지를 성공적으로 읽지 만 urllib2.urlopen은 읽지 않습니다.urllib.urlopen하지만 작동하지 않습니다 urllib2.urlopen

Traceback (most recent call last): 
    File "urltest.py", line 5, in <module> 
    print urllib2.urlopen("http://127.0.0.1").read() 
    File "C:\Python25\lib\urllib2.py", line 121, in urlopen 
    return _opener.open(url, data) 
    File "C:\Python25\lib\urllib2.py", line 380, in open 
    response = meth(req, response) 
    File "C:\Python25\lib\urllib2.py", line 491, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "C:\Python25\lib\urllib2.py", line 412, in error 
    result = self._call_chain(*args) 
    File "C:\Python25\lib\urllib2.py", line 353, in _call_chain 
    result = func(*args) 
    File "C:\Python25\lib\urllib2.py", line 575, in http_error_302 
    return self.parent.open(new) 
    File "C:\Python25\lib\urllib2.py", line 380, in open 
    response = meth(req, response) 
    File "C:\Python25\lib\urllib2.py", line 491, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "C:\Python25\lib\urllib2.py", line 418, in error 
    return self._call_chain(*args) 
    File "C:\Python25\lib\urllib2.py", line 353, in _call_chain 
    result = func(*args) 
    File "C:\Python25\lib\urllib2.py", line 499, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 504: Gateway Timeout 

어떤 아이디어 :

import urllib, urllib2 
print urllib.urlopen("http://127.0.0.1").read() # prints "running" 
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception 

여기에 스택 추적이있다 : 여기에 문제가 (이 실제 스크립트가 아닌 다른 테스트 스크립트의 단순화)을 보여줍니다 스크립트입니까? 내가 urllib2의 고급 기능 중 일부를 필요로하게 될 수도 있으므로 urllib을 사용하여 더 이상이 문제를 이해하고 싶지는 않습니다.

답변

16

는 소리 (파이썬 2.5.2와 WINXP) "내 컴퓨터에서 잘 작동합니다." "127.0.0.01/"프록시를 시도 할 때 프록시가 포기하고 504 오류를 반환합니다. Obscure python urllib2 proxy gotcha에서

:

proxy_support = urllib2.ProxyHandler({}) 
opener = urllib2.build_opener(proxy_support) 
print opener.open("http://127.0.0.1").read() 

# Optional - makes this opener default for urlopen etc. 
urllib2.install_opener(opener) 
print urllib2.urlopen("http://127.0.0.1").read() 
+0

스크립트가 3 줄 밖에 없었고 프록시에 대해 아무 것도 나타내지 않는 환경 변수가 없기 때문에이 방법으로 프록시를 사용하는 방법이나 이유를 알 수는 없지만 문제가 해결되었습니다. 그래도 해결 된 것이 좋으므로 도움을 주셔서 감사합니다. –

+0

OpenerDirector 인스턴스에 'urlopen'속성이 없습니다. 위의 프래그먼트를 opener.open (...으로 변경해야합니다. – ryan

1

urllib2.open 다음에 urllib.open을 먼저 호출해도 동일한 결과가 나타 납니까? 첫 번째 호출이 열려 있으면 http 서버가 시간 초과로 인해 바쁠 수 있는지 궁금하십니까?

+0

아니요. urllib2는 먼저 호출되었는지 여부에 관계없이 오류를 가져오고 urllib는 여러 번 호출 되더라도 오류를 가져 오지 않습니다. 좋은 생각. –

1

나는이 대답은 짜증 알아,하지만 당신은 urllib2를가 픽업되는 것을 정의 된 프록시 설정을 가지고있는 것처럼

+0

필자도 Windows XP에서 Python 2.5.2를 실행 중이므로 흥미 롭습니다. 한번 해줘서 고마워. –

1

내가 무슨 일이 일어나고 있는지 모르겠지만, 당신이 그것을 파악이 도움을 찾을 수 있습니다 :

>>> import urllib2 
>>> urllib2.urlopen('http://mit.edu').read()[:10] 
'<!DOCTYPE ' 
>>> urllib2._opener.handlers[1].set_http_debuglevel(100) 
>>> urllib2.urlopen('http://mit.edu').read()[:10] 
connect: (mit.edu, 80) 
send: 'GET/HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: mit.edu\r\nConnection: close\r\nUser-Agent: Python-urllib/2.5\r\n\r\n' 
reply: 'HTTP/1.1 200 OK\r\n' 
header: Date: Tue, 14 Oct 2008 15:52:03 GMT 
header: Server: MIT Web Server Apache/1.3.26 Mark/1.5 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.7c 
header: Last-Modified: Tue, 14 Oct 2008 04:02:15 GMT 
header: ETag: "71d3f96-2895-48f419c7" 
header: Accept-Ranges: bytes 
header: Content-Length: 10389 
header: Connection: close 
header: Content-Type: text/html 
'<!DOCTYPE ' 
1

urllib.urlopen()는 다음과 같은 요청을 던졌습니다 서버에서 :

GET/HTTP/1.0 
Host: 127.0.0.1 
User-Agent: Python-urllib/1.17 

는 urllib2.urlopen()이 발생하면서 :

GET/HTTP/1.1 
Accept-Encoding: identity 
Host: 127.0.0.1 
Connection: close 
User-Agent: Python-urllib/2.5 

따라서 서버는 HTTP/1.1 또는 추가 헤더 필드를 인식하지 못합니다.