How do I send a custom header with urllib2 in a HTTP Request?

前端 未结 3 1673
傲寒
傲寒 2020-12-01 03:03

I want to send a custom \"Accept\" header in my request when using urllib2.urlopen(..). How do I do that?

3条回答
  •  天命终不由人
    2020-12-01 03:41

    Not quite. Creating a Request object does not actually send the request, and Request objects have no Read() method. (Also: read() is lowercase.) All you need to do is pass the Request as the first argument to urlopen() and that will give you your response.

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

提交回复
热议问题