python实现HTTP请求的三中方式:urllib2/urllib、httplib/urllib 以及Requests

urllib2/urllib实现

urllib2和urllib是python两个内置的模块,要实现HTTP功能,实现方式是以urllib2为主,urllib为辅

1 首先实现一个完整的请求与响应模型

  • urllib2提供基础函数urlopen,
import urllib2
response = urllib2.urlopen('http://www.cnblogs.com/guguobao')
html = response.read()
print html
  • 改进,分两步:请求和响应
#!coding:utf-8
import urllib2
#请求
request = urllib2.Request('http://www.cnblogs.com/guguobao')
#响应
response = urllib2.urlopen(request)
html = response.read()
print html
  • 上面使用GET请求,下面改为POST请求,使用urllib。
#!coding:utf-8
import urllib
import urllib2
url = 'http://www.cnblogs.com/login'
postdata = {'username' : 'qiye',
'password' : 'qiye_pass'}
#info 需要被编码为urllib2能理解的格式,这里用到的是urllib
data = urllib.urlencode(postdata)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
html = response.read()
    • 然而运行结果没有输出,因为服务器拒绝你的访问,需要检验请求头信息,来判断是否是来自浏览器的请求

2 请求头headers处理

  • 把上面的列子添加User-Agent域和Referer域信息

    • User-Agent:有些服务器或Proxy会检查该值是否是浏览器发出的信息
    • Content-Type:在使用REST接口时,服务器会检查该值,确定HTTP body用什么解析。否则报错,拒绝回应。取值详情:http://www.runoob.com/http/http-content-type.html
    • Referer:服务器检查防盗链
#coding:utf-8
#请求头headers处理:设置一下请求头中的User-Agent域和Referer域信息
import urllib
import urllib2
url = 'http://www.xxxxxx.com/login'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
referer='http://www.xxxxxx.com/'
postdata = {'username' : 'qiye',
'password' : 'qiye_pass'}
# 将user_agent,referer写入头信息
headers={'User-Agent':user_agent,'Referer':referer}
data = urllib.urlencode(postdata)
req = urllib2.Request(url, data,headers)
response = urllib2.urlopen(req)
html = response.read()

3 Cookie处理

  • urllib2对Cookie的处理也是自动,使用CookieJar函数进行Cookie的管理,如果需要得到某个Cookie项的值,可以这样:
import urllib2,cookielib

cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open('http://www.zhihu.com')
for item in cookie:
print item.name+':'+item.name
  • 但有时遇到情况,我们不想让urllib2自动处理,我们想自己添加Cookie的内容,可以通过设置请求头中的cookie域来做
import urllib2,cookielib

opener = urllib2.build_opener()
opener.addheaders.append(('Cookie','email='+'helloguguobao@gmail.com'))#Cookie和email替换什么值都可以,但不能没有
req = urllib2.Request('http://www.zhihu.com')
response = opener.open(req)
print response.headers
retdata = response.read()
  • 运行截图

4 设置Timeout超时

  • 在python2.6及新版中,urlopen函数提供对Timeout的设置:
import urllib2
request=urllib2.Request('http://www.zhihu.com')
response = urllib2.urlopen(request,timeout=2)
html=response.read()
print html

5 获取HTTP响应码

  • 只要使用urlopen返回的response对象的getcode()方法就可以得到HTTP返回码。
import urllib2
try:
response = urllib2.urlopen('http://www.google.com')
print response
except urllib2.HTTPError as e:
if hasattr(e, 'code'):
print 'Error code:',e.code

6. 重定向

  • urllib2默认情况下会对HTTP 3XX返回码自动进行重定向动作。要检测是否发生重定向动作,只要检查一下Response的URL和Request的URL是否一致:
import urllib2
response = urllib2.urlopen('http://www.zhihu.cn')
isRedirected = response.geturl() == 'http://www.zhihu.cn'
  • 如果不想自动重定向,可以自定义HTTPRedirectHandler类:
import urllib2
class RedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
pass
def http_error_302(self, req, fp, code, msg, headers):
result =urllib2.HTTPRedirectHandler.http_error_301(self,req,fp,code,msg,headers)
result.status =code
result.newurl = result.geturl()
return result opener = urllib2.build_opener(RedirectHandler)
opener.open('http://www.zhihu.cn')

7 Proxy的设置

  • 在做爬虫开发中,可能会用到代理。urllib2默认会使用环境变量http_proxy来设置HTTP Proxy。但是我们一般不采用这种方法,而是使用ProxyHandler在程序中动态设置代理
import urllib2
proxy = urllib2.ProxyHandler({'http': '127.0.0.1:1080'})# 运行时需要把socketsocks关闭系统代理。并使用1080端口,或者直接退出socketsocks软件
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
response = urllib2.urlopen('http://www.zhihu.com/')
print response.read()

这里要注意一个细节,使用urllib2.install_opener()会设置urllib2的全局opener,之后,所有的HTTP访问都会使用这个代理,这样很方便,但是,想在程序中使用两个不同的代理,就不能使用install_opener去更改全局的设置,而是直接调用urllib2.open()

import urllib2
proxy = urllib2.ProxyHandler({'http': '127.0.0.1:1080'})
opener = urllib2.build_opener(proxy,)
response = opener.open("http://www.google.com/")
print response.read()

运行时需要把socketsocks关闭系统代理。

HTTP请求的python实现(urlopen、headers处理、 Cookie处理、设置Timeout超时、 重定向、Proxy的设置)的更多相关文章

  1. Python中urlopen()介绍

    #以下介绍是基于Python3.4.3 一.  简介   urllib.request.urlopen()函数用于实现对目标url的访问. 函数原型如下:urllib.request.urlopen( ...

  2. 【转】提交http请求之python与curl

    提交http请求之python与curl 由于Openstack是python实现wsgi的REST ful架构,在学习和调试的过程中,常常会遇到http请求的提交,于是顺手整理下python和cur ...

  3. 用python模拟登录(解析cookie + 解析html + 表单提交 + 验证码识别 + excel读写 + 发送邮件)

    老婆大人每个月都要上一个网站上去查数据,然后做报表. 为了减轻老婆大人的工作压力,所以我决定做个小程序,减轻我老婆的工作量. 准备工作 1.tesseract-ocr 这个工具用来识别验证码,非常好用 ...

  4. python爬虫 - Urllib库及cookie的使用

    http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...

  5. Python爬虫入门六之Cookie的使用

    大家好哈,上一节我们研究了一下爬虫的异常处理问题,那么接下来我们一起来看一下Cookie的使用. 为什么要使用Cookie呢? Cookie,指某些网站为了辨别用户身份.进行session跟踪而储存在 ...

  6. python爬虫(六) Cookie

    什么是Cookie 在网站中,http的请求通常是无状态的(第一个和服务器连接并且登录之后,此时服务器知道是哪个用户,但是当第二次请求服务器时,服务器依然不知道当前请求的是哪个用户),cookie就是 ...

  7. python 接口自动化测试(五)其他-认证&代理&超时配置

    有了前面几节的介绍,基本的接口测试是可以满足了.本节一些其它的高级技巧: 一.认证 1.基本认证: # -*- coding:utf-8 -*- import requests url = " ...

  8. 【python】-- Django 分页 、cookie、Session、CSRF

    Django  分页 .cookie.Session.CSRF 一.分页 分页功能在每个网站都是必要的,下面主要介绍两种分页方式: 1.Django内置分页 from django.shortcuts ...

  9. Ajax跨域请求action方法,无法传递及接收cookie信息(应用于系统登录认证及退出)解决方案

    最近的项目中涉及到了应用ajax请求后台系统登录,身份认证失败,经过不断的调试终于找到解决方案. 应用场景: 项目测试环境:前端应用HTML,js,jQuery ajax请求,部署在Apache服务器 ...

随机推荐

  1. docker及k8s安装consul

    一.docker部署consul集群 参考文献:https://www.cnblogs.com/lonelyxmas/p/10880717.html https://blog.csdn.net/qq_ ...

  2. python---硬件序列号

    安装wmi : pip install wmi -i https://pypi.douban.com/simple 还要安装  pip install pywin32 import wmi c = w ...

  3. vue3.0以上关于打包后出现空白页和路由不起作用

    1.解决页面空白,找不到资源 在项目根目录中的vue.config.js中publicPath: '/'修改为publicPath: './',如果没有这个文件,新建一个,基础代码为: module. ...

  4. java 项目 文件关系 扫描 注释注入(2)

    https://www.cnblogs.com/daimajun/p/7152970.html(copy) 先提一嘴 @RequestMapping(“url”),这里的 url写的是请求路径的一部分 ...

  5. LA 6434 The Busiest City dfs

    Tree Land Kingdom is a prosperous and lively kingdom. It has N cities which are connected to eachoth ...

  6. CDOJ 1255 斓少摘苹果 图论 2016_5_14

    斓少摘苹果 Time Limit: 3000/3000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit  St ...

  7. 使用python 将地址链接变成二维码

    import os from MyQR import myqr myqr.run( words='https://sz.ke.com/?utm_source=baidu&utm_medium= ...

  8. HDU 1711:Number Sequence(KMP)

    Number Sequence Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  9. [CSP-S模拟测试]:慢无止境的八月(乱搞)

    题目传送门(内部题102) 输入格式 第一行三个正整数$n,k,q$,分别表示数列长度,操作长度和修改个数. 第二行$n$个数,表示给出的终止数列. 接下来$q$行,每行两个数$pos,dx$,表示将 ...

  10. 「JOI 2019 Final」 硬币收藏

    题目链接 戳我 \(Solution\) 先将所有棋子移动到最近的目标点上 我们设两个变量\(ans1,ans2\)表示到目前为止这个点上可以移动棋子的数目,然后\(f[i][j]\)表示\((i,j ...