아미(아름다운미소)

urllib2: 무엇을 받고 있는 거지? 본문

랭귀지/PYTHON

urllib2: 무엇을 받고 있는 거지?

유키공 2017. 12. 19. 20:30

HTTP 요청을 전송하면, html이나 이미지 또는 비디오 등등이 돌아온다.

어떤 경우에는 받고 있는 데이터의 유형 예상대로 인지 점검해야 한다.

받고 있는 문서의 유형을 점검하려면, MIME 유형을 보자 (Content-type) 헤더:

urlfile = urllib2.urlopen('http://www.commentcamarche.net/')
print "Document type is", urlfile.info().getheader("Content-Type","")


이는 다음과 같이 출력된다:

Document type is text/html


경고: 쌍반점 다음에 정보가 있을  있다. 예를 들어:

Document type is text/html; charset=iso-8859-1


그래서 언제나 다음과 같이 하면:

print "Document type is", urlfile.info().getheader("Content-Type","").split(';')[0].strip()


오직 "text/html" 부분만 얻을  있다.



주목하자. .info() 또한 다른 HTTP 응답 헤더도 돌려준다:

print "HTTP Response headers:"
print urlfile.info()


다음과 같이 인쇄된다:

Document type is Date: Thu, 23 Mar 2006 15:13:29 GMT
Content-Type: text/html; charset=iso-8859-1
Server: Apache
X-Powered-By: PHP/5.1.2-1.dotdeb.2
Connection: close

'랭귀지 > PYTHON' 카테고리의 다른 글

[python]crawler 샘플  (0) 2017.12.21
Python 에서 Mysql 사용 하기  (0) 2017.12.20
urllib2로 에러 처리하는 법  (0) 2017.12.19
urllib2 그리고 프록시  (0) 2017.12.19
SQLite - 단순하게 만든 데이터베이스  (0) 2017.12.19
Comments