Program Tip

파이썬의 urllib를 사용하여 헤더를 어떻게 설정합니까?

programtip 2020. 11. 16. 22:05
반응형

파이썬의 urllib를 사용하여 헤더를 어떻게 설정합니까?


나는 파이썬의 urllib에 꽤 익숙합니다. 내가해야 할 일은 서버로 전송되는 요청에 대한 사용자 지정 헤더를 설정하는 것입니다. 특히 Content-type 및 Authorizations 헤더를 설정해야합니다. 파이썬 문서를 조사했지만 찾을 수 없었습니다.


urllib2를 사용하여 HTTP 헤더 추가 :

문서에서 :

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

Python 3과 Python 2 모두 다음과 같이 작동합니다.

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)

urllib2를 사용하고 urlopen에 전달하는 Request 객체를 만듭니다. http://docs.python.org/library/urllib2.html

더 이상 "오래된"urllib를 사용하지 않습니다.

req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()

테스트되지 않은 ....


여러 헤더의 경우 다음과 같이하십시오.

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

참고 URL : https://stackoverflow.com/questions/7933417/how-do-i-set-headers-using-pythons-urllib

반응형