어쩌면 당신은 방금 가져온 페이지가 무엇을 말하는 지 알기 위해 requested.read()를 봐야 할 것입니다. :) 또한 서버가 보낸 헤더에 대한 requested.info()를보십시오.
그리고 오류를 잡으려면 try: ... except:
에서이 작업을 수행해야합니다. docs.python.org/2/howto/urllib2.html을 참조하십시오.
FWIW, 현대적인 접근 방식은 요청 모듈을 사용하는 것입니다.
편집
여기에 내가 몇 년 전에 몇 쓴 일부 코드에서 발췌 한 것입니다.
import urllib2
def post(url, params):
txdata = urllib.urlencode(params)
try:
# create a request object
req = urllib2.Request(url, txdata)
# and open it to return a handle on the url
handle = urllib2.urlopen(req)
except IOError, e:
print >>sys.stderr, 'We failed to open "%s".' % url
if hasattr(e, 'code'):
print >>sys.stderr, 'We failed with error code - %s.' % e.code
elif hasattr(e, 'reason'):
print >>sys.stderr, "The error object has the following 'reason' attribute :"
print >>sys.stderr, e.reason
print >>sys.stderr, "This usually means the server doesn't exist,"
print >>sys.stderr, "is down, or we don't have an internet connection."
#raise SystemExit, 1
raise
else:
print >>sys.stderr, 'Here are the headers of the page :\n%s\n' % handle.info()
true_url = handle.geturl()
print >>sys.stderr, "\nTrue URL = '%s'\n" % true_url
return true_url
몇 가지 아이디어가 있기를 바랍니다. 당신이 요청 객체를 만들기 전에
2
가 쿠키를 처리하기 위해 편집, 그냥 이렇게 :
# build opener with HTTPCookieProcessor
cookie_handler = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookie_handler)
urllib2.install_opener(opener)
내가 다른 모듈을 사용하는 것보다 더 효과적인 기술을 사용하고 싶습니다 :/ – user3818650
FWIW을, I urllib2 (및 urllib) 만 사용했습니다. 요청이 매우 인기 있고 사용하기가 더 쉽기 때문에 요청에 대해 언급했습니다. 하지만 어쨌든 앞서 말했듯이, 여러분의 프로그램은 예외 처리를해야하며, 서버가 보낸 헤더의 응답 코드 등을 봐야합니다. request.info()에서 찾을 수 있습니다. 원한다면 위의 대답에 간단한 예제 코드를 붙여 넣을 것입니다. –
나는 정말 그랬 으면 좋겠다 :) – user3818650