どのように私は、HTTPリクエストにurllib2のにカスタムヘッダを送信するのですか?

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

  •  23-08-2019
  •  | 
  •  

質問

私は、カスタムurllib2.urlopenを使用している場合(..)私のリクエストのヘッダーを「同意する」を送りたいです。私はそれを行う方法を教えてください。

役に立ちましたか?

解決

未かなり。 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