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

## 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=‘+‘[email protected]‘))#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关闭系统代理。

原文地址:https://www.cnblogs.com/guguobao/p/9403730.html

时间: 2024-08-04 08:58:51

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

Python中urlopen()介绍

#以下介绍是基于Python3.4.3 一.  简介   urllib.request.urlopen()函数用于实现对目标url的访问. 函数原型如下:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) 函数定义如下: def urlopen(url, data=None, timeout=socket._GLOBAL_DEFA

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

老婆大人每个月都要上一个网站上去查数据,然后做报表. 为了减轻老婆大人的工作压力,所以我决定做个小程序,减轻我老婆的工作量. 准备工作 1.tesseract-ocr 这个工具用来识别验证码,非常好用. ubuntu上安装: sudo apt-get install tesseract-ocr 非常简单. 2.pytesseract和PIL(pillow) pytesseract用来在python中调用tesseract-ocr,PIL(pillow)用来加载图片,安装方法如下: pip3 in

Python爬虫入门六之Cookie的使用

大家好哈,上一节我们研究了一下爬虫的异常处理问题,那么接下来我们一起来看一下Cookie的使用. 为什么要使用Cookie呢? Cookie,指某些网站为了辨别用户身份.进行session跟踪而储存在用户本地终端上的数据(通常经过加密) 比如说有些网站需要登录后才能访问某个页面,在登录之前,你想抓取某个页面内容是不允许的.那么我们可以利用Urllib2库保存我们登录的Cookie,然后再抓取其他页面就达到目的了. 在此之前呢,我们必须先介绍一个opener的概念. 1.Opener 当你获取一个

python之路_day70_django中cookie介绍

一.django模板系统 1.母板 为其他子模板文件所共有的内容文件,各子模板的不同部分通过模板语言占位.注意:我们通常会在母板中定义页面专用的CSS块和JS块,方便子页面替换,如下例: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" con

python subprocess模块 监控子进程的2种方式 忙等待和立即返回同时设置子进程超时

下面的资料是关于python subprocess模块 监控子进程的2种方式 忙等待和立即返回同时设置子进程超时时间的代码. import subprocess import os import time tt = '555' cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt print time.time() sub2 = subprocess.Pope

【转】python下urlopen和urlretrieve的区别

1.urlopen()方法urllib.urlopen(url[, data[, proxies]]) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远程数据.参数url表示远程数据的路径,一般是网址:参数data表示以post方式提交到url的数据(玩过web的人应该知道提交数据的两种方式:post与get.如果你不清楚,也不必太在意,一般情况下很少用到这个参数):参数proxies用于设置代理.urlopen返回 一个类文件对象,它提供了如下方法:read(

获取跨域请求的自定义的response headers

一般情况下,使用ajax的getAllResponseHeaders这个方法只能得到response headers中的content-type的信息,其他服务器端放入response header中的信息并不能被获取, 我们需要做的配置是:在服务端的headers中多加一个Access-Control-Expose-Headers,后面可以有多个内容,以逗号分开. 这样的话我们就可以获取response headers中自定义的信息了 不过我还是想多bb一些自己对于http通信的理解,在我粗浅

axiso发送网络请求及python接收处理

安装$ npm install axios 1.发送get请求: axios.get("/api/v1.0/cars?id=132").then(function(res){ console.log(res) }).catch(function(err){ console.log(err) }); 2.发送post请求: let params = { id:4, ctime:'2019-03-1',name:"奔驰4" } //'Content-Type':'app

需要auth验证的post请求(python)

#!/usr/bin/python3.5 # import sys, requests try:     host = sys.argv[1] except IndexError:     sys.exit('Usage: {0} host'.format(sys.argv[0]))      user = 'root' passwd = '123' url = 'http://{0}/xcache/cacher/'.format(host) headers = {'User-Agent':'M