对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创建属于自己的单词词库 便于背单词

python创建属于自己的单词词库 便于背单词

本文实例为大家分享了python创建单词词库的具体代码,供大家参考,具体内容如下 基本思路:以COCA两万单词表为基础,用python爬取金山词霸的单词词性,词义,音频分别存入sqlli...

用Python中的__slots__缓存资源以节省内存开销的方法

用Python中的__slots__缓存资源以节省内存开销的方法

我们曾经提到,Oyster.com的Python web服务器怎样利用一个巨大的Python dicts(hash table),缓存大量的静态资源。我们最近在Image类中,用仅仅一行...

使用python3实现操作串口详解

通过引用serial模块包,来操作串口。 1、查看串口名称 在Linux和Windows中,串口的名字规则不太一样。 需要事先查看。 Linux下的查看串口命令 root@D2:...

利用Python中的pandas库对cdn日志进行分析详解

前言 最近工作工作中遇到一个需求,是要根据CDN日志过滤一些数据,例如流量、状态码统计,TOP IP、URL、UA、Referer等。以前都是用 bash shell 实现的,但是当日志...

python实现的udp协议Server和Client代码实例

直接上代码:Server端:复制代码 代码如下: #!/usr/bin/env python # UDP Echo Server -  udpserver....