Python에서 urllib2 (및 urllib)를 사용하여 Google과 같은 외부 URL을 열 수 있습니다. 그러나 localhost URL을 열 때 문제가 발생합니다. 나는 성공적으로 http://localhost:8280/을 사용하여 탐색 할 수있는 포트 8280에서 실행되는 Python SimpleHTTPServer를 가지고있다.Python urllib 및 urllib2가 localhost URL을 열지 못합니까?
python -m SimpleHTTPServer 8280
그것은 또한 내가 CNTLM 우리 기업의 웹 프록시 인증을 처리하는 실행이 우분투를 실행하는거야 있음을 주목할 필요가있다. 그러므로 wget은 실제로 localhost와 함께 작동하지 않으므로 urllib 문제는 아닙니다.
테스트 스크립트 (test_urllib2.py) :
import urllib2
print "Opening Google..."
google = urllib2.urlopen("http://www.google.com/")
print google.read(100)
print "Google opened."
print "Opening localhost..."
localhost = urllib2.urlopen("http://localhost:8280/")
print localhost.read(100)
print "localhost opened."
출력 :
$ ./test_urllib2.py
Opening Google...
<!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><
Google opened.
Opening localhost...
Traceback (most recent call last):
File "./test_urllib2.py", line 10, in <module>
localhost = urllib2.urlopen("http://localhost:8280/")
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 397, in open
response = meth(req, response)
File "/usr/lib/python2.6/urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.6/urllib2.py", line 429, in error
result = self._call_chain(*args)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 605, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1134, in do_open
r = h.getresponse()
File "/usr/lib/python2.6/httplib.py", line 986, in getresponse
response.begin()
File "/usr/lib/python2.6/httplib.py", line 391, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.6/httplib.py", line 355, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine
해결책 : 이유 나는 우리 회사의 웹 프록시 뒤에 CNTLM를 사용하고 있기 때문에 문제가 참이었다 (세부 사항 이것은 내가 확신 할 수없는 문제를 야기했다). 나에게 here을 가리키는 위해 loki2302하는
proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
print opener.open("http://localhost:8380/").read(100)
감사 :이 솔루션은 ProxyHandler를 사용하는 것이 었습니다.
예외없이 'except :'를 사용하지 말고'urllib2.urlopen'에 의해 발생한 예외를 우리에게 보여 주라. – mouad
http://stackoverflow.com/questions/201515/urllib-urlopen-works-but-urllib2-urlopen-doesnt – agibalov
'BadStatusLine' 예외는 서버의 잘못된 응답 헤더를 나타냅니다. 당신은 엿봄을 가지고 있고 돌려 보내지고있는 무슨을 볼 수 있 었는가? –