对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 实现堆排序算法代码

复制代码 代码如下: #!/usr/bin/python import sys def left_child(node): return node * 2 + 1 def right_c...

Python3实现的判断环形链表算法示例

本文实例讲述了Python3实现的判断环形链表算法。分享给大家供大家参考,具体如下: 给定一个链表,判断链表中是否有环。 方案一:快慢指针遍历,若出现相等的情况,说明有环 # Def...

对Python中DataFrame按照行遍历的方法

在做分类模型时候,需要在DataFrame中按照行获取数据以便于进行训练和测试。 import pandas as pd dict=[[1,2,3,4,5,6],[2,3,4,5,6...

Python 多维List创建的问题小结

背景 最近在学Python,我觉得学习一个新语言最好的方式就是写一个简单的项目,所以就打算写一个简单的俄罗斯方块游戏。那么在写的过程中遇到了一个小问题。 def __init__...

Pycharm简单使用教程(入门小结)

Pycharm简单使用教程(入门小结)

1、下载pycharm pycharm是一种Python IDE,能够帮助我们在编写代码时提高效率。 网上提供的有专业版和教育版之分。 专业版是收费的,功能更全面点。 教育版...