对Python发送带header的http请求方法详解

只有相信自己的目标,努力工作和奋斗的人才能取得最终的成功。但是我一直相信的一件事是,当您触摸自己哭泣时,您就成功了!

简单的header

import urllib2
 
request = urllib2.Request('http://example.com/')
request.add_header('User-Agent', 'fake-client')
response = urllib2.urlopen(request)
print request.read()

包含较多元素的header

import urllib,urllib2
 
url = 'http://example.com/'
headers = { 'Host':'example.com',
          'Connection':'keep-alive',
          'Cache-Control':'max-age=0',
          'Accept': 'text/html, */*; q=0.01',
          'X-Requested-With': 'XMLHttpRequest',
          'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
          'DNT':'1',
          'Referer': 'http://example.com/',
          'Accept-Encoding': 'gzip, deflate, sdch',
          'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6'
}
data = None
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
html = response.read()

以上这篇对Python发送带header的http请求方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战