零基础写python爬虫之urllib2使用指南

2019-10-05 14:58:51王振洲


import urllib2 
my_url = 'http://www.google.cn' 
response = urllib2.urlopen(my_url) 
redirected = response.geturl() == my_url 
print redirected 
my_url = 'http://rrurl.cn/b1UZuP' 
response = urllib2.urlopen(my_url) 
redirected = response.geturl() == my_url 
print redirected 

如果不想自动 redirect,除了使用更低层次的 httplib 库之外,还可以自定义HTTPRedirectHandler 类。


import urllib2 
class RedirectHandler(urllib2.HTTPRedirectHandler): 
    def http_error_301(self, req, fp, code, msg, headers): 
        print "301" 
        pass 
    def http_error_302(self, req, fp, code, msg, headers): 
        print "303" 
        pass  
opener = urllib2.build_opener(RedirectHandler) 
opener.open('http://rrurl.cn/b1UZuP') 

5.Cookie

urllib2 对 Cookie 的处理也是自动的。如果需要得到某个 Cookie 项的值,可以这么做:


import urllib2 
import cookielib 
cookie = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) 
response = opener.open('http://www.baidu.com') 
for item in cookie: 
    print 'Name = '+item.name 
    print 'Value = '+item.value 

运行之后就会输出访问百度的Cookie值:

6.使用 HTTP 的 PUT 和 DELETE 方法

urllib2 只支持 HTTP 的 GET 和 POST 方法,如果要使用 HTTP PUT 和 DELETE ,只能使用比较低层的 httplib 库。虽然如此,我们还是能通过下面的方式,使 urllib2 能够发出 PUT 或DELETE 的请求:


import urllib2 
request = urllib2.Request(uri, data=data) 
request.get_method = lambda: 'PUT' # or 'DELETE' 
response = urllib2.urlopen(request) 

7.得到 HTTP 的返回码

对于 200 OK 来说,只要使用 urlopen 返回的 response 对象的 getcode() 方法就可以得到 HTTP 的返回码。但对其它返回码来说,urlopen 会抛出异常。这时候,就要检查异常对象的 code 属性了:


import urllib2 
try: 
    response = urllib2.urlopen('http://bbs.csdn.net/why') 
except urllib2.HTTPError, e: 
    print e.code 

8.Debug Log

使用 urllib2 时,可以通过下面的方法把 debug Log 打开,这样收发包的内容就会在屏幕上打印出来,方便调试,有时可以省去抓包的工作