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

yipeiwu_com6年前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实现词法分析器

python实现词法分析器

简单Python词法分析器实现,供大家参考,具体内容如下 词法分析器状态转换图: 词法分析器总流程图: 预处理程序: 词法分析器: 词法分析器程序详细设计 详细代码实现:...

详解Python中的type()方法的使用

 type()方法返回传递变量的类型。如果传递变量是字典那么它将返回一个字典类型。 语法 以下是type()方法的语法: type(dict) 参数  ...

python 解析html之BeautifulSoup

复制代码 代码如下:# coding=utf-8 from BeautifulSoup import BeautifulSoup, Tag, NavigableString from S...

Python编程实战之Oracle数据库操作示例

本文实例讲述了Python编程实战之Oracle数据库操作。分享给大家供大家参考,具体如下: 1. 要想使Python可以操作Oracle数据库,首先需要安装cx_Oracle包,可以通...

Python自动调用IE打开某个网站的方法

本文实例讲述了Python自动调用IE打开某个网站的方法。分享给大家供大家参考。具体实现方法如下: import win32gui import win32com import...