我们在写爬虫的时候经常会用到urllib模块,我就到网上搜集了一下urllibmokuai的使用方法,整理了一下

  模块:urllib

  环境:windows

python3版本中已经将urllib2、urlparse、和robotparser并入了urllib中,并且修改了urllib模块

这里简单介绍一下urllib模块

urllib有5种方法:

     urllib.error   ②urllib.parse  ③urllib.request   ④urllib.response  ⑤urllib.robotparser 

这里逐一介绍以上三个模块(error   parse     request) 

 urllib.request:请求模块                 

 urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)

       urlopen一般常用的有三个参数

   url:需要打开的网址

   data:默认为None,当data参数不为空的时候,提交方式为Post。

   timeout:设置网站的访问超时时间直接用urllib.request模块的urlopen()获取页面内容,返回          的数据格式为bytes类型,需要decode()解码,转换成str类型。

  

#简单的例子import urllib.requestresponse = urllib.request.urlopen('www.baidu.com')print(response.read().decode('utf-8'))

 

#或者含有data的例子import urllib.parseimport urllib.requestdata = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')print(data)response = urllib.request.urlopen('http://httpbin.org/post', data=data,timeout=10)print(response.read())

   response.geturl()  #返回请求的url地址。

          response.info()   #返回一个对象,表示远程服务器返回的头信息。

   response.getcode()  #返回Http状态码,如果是http请求,200表示请求成功完成;404表示网址未找到

    

   

   urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

   

   仅urlopen()方法可以实现最基本请求的发起,但这几个简单的参数并不足以构建一个完整的请求,如果请求中需要加入headers(请求头)等信息,我们就可以利用更强大的Request类来构建一个请求。也许这就是一下两个方式的区别

      有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访   问,最长见的有user-agent参数

       Request一般常用的有三个参数

   url:需要打开的网址

   data:默认为None,当data参数不为空的时候,提交方式为Post。

   headers:访问头部信息

#一个简单的例子from urllib import request, parseurl = 'http://httpbin.org/post'headers = {    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',    'Host': 'httpbin.org'}dict = {    'name': 'haha'}data = bytes(parse.urlencode(dict), encoding='utf8')   #将dict的参数变成name=hahareq = request.Request(url=url, data=data, headers=headers, method='POST')response = request.urlopen(req)print(response.read().decode('utf-8'))
#添加头的第二种方法from urllib import request, parseurl = 'http://httpbin.org/post'dict = {    'name': 'piupiu'}data = bytes(parse.urlencode(dict), encoding='utf8')req = request.Request(url=url, data=data, method='POST')req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')response = request.urlopen(req)print(response.read().decode('utf-8'))

    

    rullib.request.ProxyHandler()

    通过rulllib.request.ProxyHandler()可以设置代理,网站它会检测某一段时间某个IP 的访问次数,如果访问次数过多,它会禁止你的访问,所以这个时候需要通过设置代理来爬取数据

#简单的例子import urllib.requestproxy_handler = urllib.request.ProxyHandler({    'http': 'http://127.0.0.1:9743',    'https': 'https://127.0.0.1:9743'})opener = urllib.request.build_opener(proxy_handler)response = opener.open('http://httpbin.org/get')print(response.read())

    

    cookie,HTTPCookiProcessor

     cookie中保存中我们常见的登录信息,有时候爬取网站需要携带cookie信息访问,这里用到了http.cookijar,用于获取cookie以及存储cookie

import http.cookiejar, urllib.requestcookie = http.cookiejar.CookieJar()handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)response = opener.open('http://www.baidu.com')for item in cookie:    print(item.name+"="+item.value)

      同时cookie可以写入到文件中保存,有两种方式http.cookiejar.MozillaCookieJar和http.cookiejar.LWPCookieJar(),当然你自己用哪种方式都可以

      

      http.cookiejar.MozillaCookieJar()方式

import http.cookiejar, urllib.requestfilename = "cookie.txt"cookie = http.cookiejar.MozillaCookieJar(filename)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)response = opener.open('http://www.baidu.com')cookie.save(ignore_discard=True, ignore_expires=True)

     

       http.cookiejar.LWPCookieJar()方式

import http.cookiejar, urllib.requestfilename = 'cookie.txt'cookie = http.cookiejar.LWPCookieJar(filename)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)response = opener.open('http://www.baidu.com')cookie.save(ignore_discard=True, ignore_expires=True)

    

    urllib.error:   异常处理模块

    在很多时候我们通过程序访问页面的时候,有的页面可能会出现错误,类似404,500等错误
这个时候就需要我们捕捉异常

#一个简单的例子from urllib import request,errortry:    response = request.urlopen("http://pythonsite.com/1111.html")except error.URLError as e:    print(e.reason)

上述代码访问的是一个不存在的页面,通过捕捉异常,我们可以打印异常错误

这里我们需要知道的是在urllb异常这里有两个个异常错误:

URLError,HTTPError,HTTPError是URLError的子类

URLError里只有一个属性:reason,即抓异常的时候只能打印错误信息,类似上面的例子

HTTPError里有三个属性:code,reason,headers,即抓异常的时候可以获得code,reson,headers三个信息,例子如下:

from urllib import request,errortry:    response = request.urlopen("http://pythonsite.com/1111.html")except error.HTTPError as e:    print(e.reason)    print(e.code)    print(e.headers)except error.URLError as e:    print(e.reason)else:    print("reqeust successfully")

同时,e.reason其实也可以在做深入的判断,例子如下:

import socketfrom urllib import error,requesttry:    response = request.urlopen("http://www.pythonsite.com/",timeout=0.001)except error.URLError as e:    print(type(e.reason))    if isinstance(e.reason,socket.timeout):        print("time out")

  

     urllib.parse:   url解析模块

from urllib.parse import urlparseresult = urlparse("print(result)

执行结果如下:

这里就是可以对你传入的url地址进行拆分
同时我们是可以指定协议类型:
result = urlparse(")
这样拆分的时候协议类型部分就会是你指定的部分,当然如果你的url里面已经带了协议,你再通过scheme指定的协议就不会生效

     

     urlunpars

其实功能和urlparse的功能相反,它是用于拼接,例子如下:

from urllib.parse import urlunparsedata = ['http','print(urlunparse(data))

执行结果如下:

   

    urljoin

这个的功能其实是做拼接的

from urllib.parse import urljoinprint(urljoin('http://www.baidu.com', 'FAQ.html'))print(urljoin('http://www.baidu.com', 'https://pythonsite.com/FAQ.html'))print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html'))print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html?question=2'))print(urljoin('http://www.baidu.com?wd=abc', 'https://pythonsite.com/index.php'))print(urljoin('http://www.baidu.com', '?category=2#comment'))print(urljoin('www.baidu.com', '?category=2#comment'))print(urljoin('www.baidu.com#comment', '?category=2'))

执行结果如下:

 

从拼接的结果我们可以看出,拼接的时候后面的优先级高于前面的url

  

      urlencode

  这个方法可以将字典转换为url参数 

from urllib.parse import urlencodeparams = {    "name":"zhaofan",    "age":23,}base_url = "http://www.baidu.com?"url = base_url+urlencode(params)print(url)

执行结果如下:

这里个人感觉下面的两种方法使用较少 就不再做分析

   

    urllib.response: 

    urllib.robotparser:   robots.txt解析模块

重要的事情说三遍

本文内容摘录与: