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

yipeiwu_com5年前Python基础

简单的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调用xlsxwriter创建xlsx的方法

详细的官方文档可见:http://xlsxwriter.readthedocs.io/ 通过pip安装xlsxwriter pip install xlsxwriter 下面进行基...

Windows下实现Python2和Python3两个版共存的方法

一直用的是python2,从python 2.3到python 2.7.6, 出于想了解python3的新特性,又安装了python3.3.3. 用了才发现蛮方便的。python的各个版...

Python元组知识点总结

Python的元组与列表类似,不同之处在于元组的元素不能修改。 元组使用小括号,列表使用方括号。 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。 如下实例: tu...

Python实现的径向基(RBF)神经网络示例

本文实例讲述了Python实现的径向基(RBF)神经网络。分享给大家供大家参考,具体如下: from numpy import array, append, vstack, tran...

Python实现批量将word转html并将html内容发布至网站的方法

本文实例讲述了Python实现批量将word转html并将html内容发布至网站的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 __author__ =...