Python网络编程中urllib2模块的用法总结
Aug 04, 2016 am 08:55 AM一、最基础的应用
import urllib2 url = r'http://www.baidu.com' html = urllib2.urlopen(url).read() print html
客户端与服务器端通过request与response来沟通,客户端先向服务端发送request,然后接收服务端返回的response
urllib2提供了request的类,可以让用户在发送请求前先构造一个request的对象,然后通过urllib2.urlopen方法来发送请求
import urllib2 url = r'http://www.baidu.com' req = urllib2.Request(url) html = urllib2.urlopen(req).read() print html
上例中先使用
req = urllib2.Request(url)
实例化一个resquest对象,接下来使用
urllib2.urlopen(req)
来打开这个网页。
我们注意到在实例化Request对象的时候,队了url是必须的,还有几个默认的参数
基中data与header也是使用的比较多的,一些需要登录的才能浏览的网站经常需要这两个参数
import urllib import urllib2 url = 'http://www.baidu.com/' values = {'name' : 'Michael Foord', 'location' : 'Northampton','language' : 'Python' } data = urllib.urlencode(values) req = urllib2.Request(url,data) response = urllib2.urlopen(req) the_page = response.read() print the_page
这个例子是向百度发送几个数据,这个例子是会返回一个错误页面,很正常,因为我们在访问百度的时候并不需要post什么信息,post了倒是会出错
百度是找不到相应的网页就会报错。
当然这个是POST数据,也可以用在GET方法,稍将上面的代码进行改造
百度是通过http://www.baidu.com/s?wd=XXX 来进行查询的,这样我们需要将{‘wd':'xxx'}这个字典进行urlencode
#coding:utf-8 import urllib import urllib2 url = 'http://www.baidu.com/s' values = {'wd':'杨彦星'} data = urllib.urlencode(values) print data url2 = url+'?'+data response = urllib2.urlopen(url2) the_page = response.read() print the_page
以下以模拟登录人人网然后再显示首页内容为例来详细说明一下cookie的使用,以下是文档中给的例子,我们就通过改造这个例子来实现我们想要的功能
import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") #coding:utf-8 import urllib2,urllib import cookielib url = r'http://www.renren.com/ajaxLogin' #创建一个cj的cookie的容器 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) #将要POST出去的数据进行编码 data = urllib.urlencode({"email":email,"password":pass}) r = opener.open(url,data) print cj
当你看到有cj的时候,说明你已经访问了登录页面,是否正常登录你现在还看不出来,可以通过访问http://www.renren.com/home 来查看
上面的代码有两点要说明,我也是看了很长时间才明白
r = opener.open(url,data)
这句,为什么要使用opener这个对象来open,而不是用utllib2,urlopen?不光是例子里这么写,我们才这么写,通过改造我们也可以使用urllib2.urlopen,其实是因为opener是urllib2.bulid_opener创造出来的, 但是你可以这样理解,他build出来后,自已却并没有安装使用它,也没有它的属性与方法,如果想使urllib2也具有opener的属性与方法,可以先使用urllib2.install_opener(opener)来"安装"这个opener,安装完以后就可以使用urllib2来操作了
#coding:utf-8 import urllib2,urllib import cookielib url = r'http://www.renren.com/ajaxLogin' #创建一个cj的cookie的容器 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) #将要POST出去的数据进行编码 data = urllib.urlencode({"email":email,"password":pass}) #r = opener.open(url,data)如果没有上面的urllib2.install_opener方法,就必须这样写了 r = urllib2.urlopen(url,data) html = urllib2.urlopen('http://www.renren.com/home').read() print html
同样urllib2还有proxy相关的handle,基本的思路和这个差不多。
二、异常处理
当urlopen()不能处理响应时会引起URLError异常。HTTPError异常是URLError的一个子类,只有在访问HTTP类型的URL时才会引起。
1、URLError异常
通常引起URLError的原因是:无网络连接(没有到目标服务器的路由)、访问的目标服务器不存在。在这种情况下,异常对象会有reason属性(是一个(错误码、错误原因)的元组)。
#! /usr/bin/env python #coding=utf-8 import urllib2 url="http://www.baidu.com/" try: response=urllib2.urlopen(url) except urllib2.URLError,e: print e.reason
2、HTTPError
每一个从服务器返回的HTTP响应都有一个状态码。其中,有的状态码表示服务器不能完成相应的请求,默认的处理程序可以为我们处理一些这样的状态码(如返回的响应是重定向,urllib2会自动为我们从重定向后的页面中获取信息)。有些状态码,urllib2模块不能帮我们处理,那么urlopen函数就会引起HTTPError异常,其中典型的有404/401。
HTTPError异常的实例有整数类型的code属性,表示服务器返回的错误状态码。
urllib2模块默认的处理程序可以处理重定向(状态码是300范围),而且状态码在100-299范围内表示成功。因此,能够引起HTTPError异常的状态码范围是:400-599.
当引起错误时,服务器会返回HTTP错误码和错误页面。你可以将HTPError实例作为返回页面,这意味着,HTTPError实例不仅有code属性,还有read、geturl、info等方法。
#! /usr/bin/env python #coding=utf-8 import urllib2 url="http://cs.scu.edu.cn/~duanlei" try: response=urllib2.urlopen(url) except urllib2.HTTPError,e: print e.code print e.read()
3、总结
如果想在代码中处理URLError和HTTPError有两种方法,代码如下:
#! /usr/bin/env python #coding=utf-8 import urllib2 url="xxxxxx" #需要访问的URL try: response=urllib2.urlopen(url) except urllib2.HTTPError,e: #HTTPError必须排在URLError的前面 print "The server couldn't fulfill the request" print "Error code:",e.code print "Return content:",e.read() except urllib2.URLError,e: print "Failed to reach the server" print "The reason:",e.reason else: #something you should do pass #其他异常的处理 #! /usr/bin/env python #coding=utf-8 import urllib2 url="http://xxx" #需要访问的URL try: response=urllib2.urlopen(url) except urllib2.URLError,e: if hasattr(e,"reason"): print "Failed to reach the server" print "The reason:",e.reason elif hasattr(e,"code"): print "The server couldn't fulfill the request" print "Error code:",e.code print "Return content:",e.read() else: pass #其他异常的处理
相比较而言,第二种异常处理方法更优。

Artikel Panas

Alat panas Tag

Artikel Panas

Tag artikel panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

Apakah kelebihan dan kekurangan templat?

Google AI mengumumkan Gemini 1.5 Pro dan Gemma 2 untuk pembangun

Dengan hanya $250, pengarah teknikal Hugging Face mengajar anda cara memperhalusi Llama 3

Kongsi beberapa rangka kerja projek berkaitan AI dan LLM sumber terbuka .NET

Panduan lengkap untuk penyahpepijatan dan analisis fungsi golang

Bagaimana anda bertanya kepadanya Deepseek

Bagaimana untuk menyimpan fungsi menilai
