对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设计】。

相关文章

简单易懂Pytorch实战实例VGG深度网络

模型VGG,数据集cifar。对照这份代码走一遍,大概就知道整个pytorch的运行机制。 来源 定义模型: '''VGG11/13/16/19 in Pytorch.'''...

Python字符串和文件操作常用函数分析

本文实例分析了Python字符串和文件操作常用函数。分享给大家供大家参考。具体如下: # -*- coding: UTF-8 -*- ''' Created on 2010-12-2...

使用python接入微信聊天机器人

本文实例为大家分享了python接入微信聊天机器人的具体代码,供大家参考,具体内容如下 1.安装库wxpy: pip install -U wxpy or pip instal...

python 反编译exe文件为py文件的实例代码

我们用pyinstaller把朋友文件打包成exe文件,但有时候我们需要还原,我们可以用pyinstxtractor.py 用法: python pyinstxtractor.py xx...

Python实现FTP上传文件或文件夹实例(递归)

本文实例讲述了Python实现FTP上传文件或文件夹实例。分享给大家供大家参考。具体如下: import sys import os import json from ftp...