对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 logging模块学习笔记

模块级函数 logging.getLogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug()、logging.in...

Python图像灰度变换及图像数组操作

Python图像灰度变换及图像数组操作

使用python以及numpy通过直接操作图像数组完成一系列基本的图像处理 numpy简介: NumPy是一个非常有名的 Python 科学计算工具包,其中包含了大量有用的工具,比如数组...

CentOS 7下安装Python3.6 及遇到的问题小结

先给大家介绍下CentOS 7下安装Python3.6 的方法 安装python3.6可能使用的依赖 yum install openssl-devel bzip2-devel ex...

python使用pip安装SciPy、SymPy、matplotlib教程

背景: 使用pip install SciPy的格式安装python函数库SciPy的时候,发现老是报错,从网上找信息也没找到合适的解决办法,最后使用whl格式文件安装成功。 过程: 本...

Python DataFrame设置/更改列表字段/元素类型的方法

Python DataFrame设置/更改列表字段/元素类型的方法

Python DataFrame 如何设置列表字段/元素类型? 比如笔者想将列表的两个字段由float64设置为int64,那么就要用到DataFrame的astype属性,举例如图:...