对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多任务及返回值的处理方法

废话不多说,直接上代码! # coding:utf-8 from multiprocessing import Pool import time def keywords(t...

pandas 根据列的值选取所有行的示例

如下所示: # 选取等于某些值的行记录 用 == df.loc[df['column_name'] == some_value] # 选取某列是否是某一类型的数值 用 isin...

python分数表示方式和写法

Fraction函数是python中实现分数的一个模块(module),模块是由别人写的,并且可以被拿来直接使用的代码程序,包括类、函数以及标签的定义,是python标准函数库的一部分。...

Python rstrip()方法实例详解

Python 字符串 描述 Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格). 语法 rstrip()方法语法: str.rstrip([chars...

Python实现的旋转数组功能算法示例

本文实例讲述了Python实现的旋转数组功能算法。分享给大家供大家参考,具体如下: 一、题目 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 例1: 输入: [...