我想在使用urllib2.urlopen(..)时在我的请求中发送自定义“Accept”标头。我怎么做?如何在HTTP请求中使用urllib2发送自定义标题?
53
A
回答
113
不完全。创建一个Request
对象实际上并不发送请求,并且请求对象没有Read()
方法。 (另外:read()
是小写字母。)您只需将Request
作为第一个参数传递给urlopen()
即可,并且会给予您答复。
import urllib2
request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"})
contents = urllib2.urlopen(request).read()
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("http://thewebsite.com", headers=request_headers)
contents = urllib2.urlopen(request).read()
print contents
1
除了已经提到的其他解决方案,你可以使用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()
相关问题
- 1. 如何使用自定义标头发送HTTP删除请求?
- 2. 如何使用urllib2发送数据和自定义标题
- 3. 发送朴素ajax HTTP请求与自定义标题
- 4. 如何发送自定义获取HTTP请求使用C#?
- 5. PHP发送自定义HTTP请求
- 6. 使用urllib2发送带有标题的发布请求
- 7. 使用cURL或socket_create发送自定义HTTP POST请求
- 8. 如何在Swagger UI中使用请求发送自定义标头?
- 9. flash.media.Sound不发送HTTP请求标题
- 10. 如何使用Telnet发送HTTP请求
- 11. 在HTTP请求中定义自定义用户代理标头?
- 12. 使用自定义标题和授权请求HTTP rest资源?
- 13. 如何通过urllib2发送HTTP/1.0请求?
- 14. 如何设置自定义HTTP请求标题
- 15. 如何添加自定义标题请求与cljs-http
- 16. 在目标c中发送HTTP请求
- 17. 如何在android中发送http请求?
- 18. 如何在Python中发送HTTP标头请求而不是HTTP
- 19. 发送一个自定义标题以及qtwebkit请求
- 20. 使用ZEND_HTTP_CLIENT发送自定义标题
- 21. Angular 4:用http请求发送自定义头文件
- 22. 如何使用ember-data向自定义URL发送请求
- 23. 如何在发布请求时在HTTP标头中设置自定义变量
- 24. 使用自定义HTTP标头发送跨域请求时禁用预检选项请求
- 25. 是否可以使用XHR(“Ajax”请求)发送自定义标题?
- 26. 发送OAuth 2.0 POST请求与自定义标题+属性值使用C#Inoreader
- 27. 自定义HTTP请求头
- 28. 发送带有HTML5音频标签的自定义HTTP请求标头
- 29. 如何发送请求标题?
- 30. 如何用PyQt发送http请求?