HTTP 요청에서 urllib2로 사용자 정의 헤더를 보내려면 어떻게합니까?

StackOverflow https://stackoverflow.com/questions/385262

  •  23-08-2019
  •  | 
  •  

문제

urllib2.urlopen (..)을 사용할 때 요청에서 사용자 정의 "수락"헤더를 보내고 싶습니다. 어떻게해야하나요?

도움이 되었습니까?

해결책

좀 빠지는. 생성 a Request 객체는 실제로 요청을 보내지 않으며 요청 객체에는 Read() 방법. (또한: read() 소문자입니다.) 당신이해야 할 일은 Request 첫 번째 논쟁으로 urlopen() 그리고 그것은 당신에게 당신의 응답을 줄 것입니다.

import urllib2
request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"})
contents = urllib2.urlopen(request).read()

다른 팁

나는 보통 사용합니다 :

import urllib2

request_headers = {
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive" 
}

request = urllib2.Request("https://thewebsite.com", headers=request_headers)
response = urllib2.urlopen(request).read()
print(response)

이미 언급 된 다른 솔루션 외에도 사용할 수 있습니다. add_header 방법.

따라서 제공된 예제는 py @pantsgolem이 다음과 같습니다.

import urllib2
request = urllib2.Request("http://www.google.com")

request.add_header('Accept','text/html')

##Show the header having the key 'Accept'
request.get_header('Accept')

response = urllib2.urlopen(request)
response.read()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top