How do I send a custom header with urllib2 in a HTTP Request?
当使用urlib2.urlopen(..)时,我想在请求中发送一个自定义的"accept"头。我该怎么做?
不完全是。创建
1 2 3 | import urllib2 request = urllib2.Request("http://www.google.com", headers={"Accept" :"text/html"}) contents = urllib2.urlopen(request).read() |
我通常使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |
号
除了前面提到的其他解决方案外,您还可以使用
所以提供的例子py@pantsgolem将是:
1 2 3 4 5 6 7 8 9 10 | 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() |