urllib库request、error、parse、robotparser模块基本使用方法

urllib库含有如下四个模块:
request模块:最基本的HTTP 请求模块,模拟浏览器发出请求。
error模块:异常处理模块,用于捕获异常。
parse模块:提供URL处理方法,比如拆分、解析、合并等。
robotparser模块:识别网站robots,txt文件,判断网站是否可爬。

本文是《Python3网络爬虫开发实战》关于urllib库request模块基本使用方法的读书笔记。

一、request模块

(一)urlopen()方法

例:爬取python官网

import urllib.request
res=urllib.request.urlopen('http://www.python.org')
print(res.read().decode('utf-8'))

打印这个http://www.python.org网页源代码。
查看urlopen()返回值的类型:

print(type(res))

可知这里得到的res是一个HTTPResponse类型的对象,主要包含的
方法:read()、readinto()、getheader(name)、getheaders()、fileno()等;
属性:msg、version、status、reason、debudlevel、closed等。

print(res.status) ###获取状态码子
print(res.getheaders()) ###获取响应的头信息
print(res.getheader('Server')) ###获取响应头中'Server'参数的值

以下是第二行输出的结果:

[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'DENY'), ('Via', '1.1 vegur'), ('Via', '1.1 varnish'), ('Content-Length', '48781'), ('Accept-Ranges', 'bytes'), ('Date', 'Sat, 15 Feb 2020 08:18:22 GMT'), ('Via', '1.1 varnish'), ('Age', '3562'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2147-IAD, cache-hkg17924-HKG'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '4, 864'), ('X-Timer', 'S1581754703.679639,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]

urlopen()函数的API:
urllib.request.urlopen(url,data=None,[timeout]*,cafile=None,capath=None,cadefault=False,context=None)
1.data参数:可选,传递此参数,请求方式由GET变为POST.
2.timeout参数:设置超时时间,以秒为单位,若超时服务器没有响应,抛出URLError异常。
例:利用try except语句实现跳过超时未响应网页。

import socket
import urllib.request
import urllib.error
try:
    response=urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')

3.context参数:是ssl.SSLContext类型,指定SSL设置。
4.cafile参数;zhiding CA证书。
5.capath参数:指定CA证书路径。
6.cadefault参数:已弃用,默认False。

(二)Request类

import urllib.request
request=urllib.request.Request('https://python.org')
response=urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
import urllib.request
response=urllib.request.urlopen('https://python.org')
print(response.read().decode('utf-8'))

(Q:这两份代码的运行结果一模一样,有啥区别?)
Request类的参数构造:
class urllib.request.Request(url,data=None,headers={},origin_req_host=None,unverifiable=False,method=None)

  • url参数:必传参数,用于请求URL。
  • data参数:选传,若传须是bytes(字节流)类型。
  • headers:字典,添加请求头。也可通过调用实例的add_header()方法添加。其最常用的方法就是通过User-Agent来伪装浏览器(P103)
  • origin_req_host参数:指请求方的host名称或者IP地址。
  • unverifiable参数:表示请求是否是无法验证的,默认是False表示用户没有足够的权限来选择接收这个请求的结果。
  • method参数:是字符串,指示请求使用的方法,比如GET、POST、PUT等。
    传入多个参数来构造一个请求:
from urllib import request,parse
url='https://httpbin.org/post'
headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64)',
    'Host':'httpbin.org'
    }
dict={  #用于参数data
    'name':'Germey'
    }
data=bytes(parse.urlencode(dict),encoding='utf-8')
req=request.Request(url=url,data=data,headers=headers,method='POST')
response=request.urlopen(req)
print(response.read().decode('utf-8'))

程序运行结果:
在这里插入图片描述
也可用过调用add_header()函数来添加headers:

from urllib import request,parse
url='https://httpbin.org/post'
dict={
    'name':'Germey'
    }
data=bytes(parse.urlencode(dict),encoding='utf-8')
req=request.Request(url=url,data=data,method='POST')
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.3; Win64; x64)')
response=request.urlopen(req)
print(response.read().decode('utf-8'))

(三)高级用法

Handler类
urllib.request模块里的BaseHandler类是所有其他Handler的父类,它提供了例如default_open()、protocol_request()等基本方法。继承于它的Handler子类有:
HTTPDefaultErrorHandler:处理HTTP响应错误,这些错误通常会抛出HTTPError类型异常。
HTTPRedirecttHandler:处理重定向。
HTTPCookieProcessor:处理Cookies。
ProxyHandler:设置代理,默认代理为空。
HTTPPasswordMgr:管理密码,维护用户名和密码的表。
HTTPBasicAuthHnadler:管理认证,如果一个链接打开时需要认证,可用它来解决认证问题。
(官方参考文档 https://docs.python.org/3/library/urllib.request.html#urllib.request.BaseHandler)

OpenerDirector(Opener)类
与Handler关系:可用Handler来构建Opener

1.HTTPBasicAuthHnadler处理网页验证:
from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener
from urllib.error import URLError

username='username'
password='password'
#url='http://authserver.gscass.cn/authserver/login?service=http%3A%2F%2Fportal.gscass.cn%2Fdcp%2Findex.jsp'
url='http://localhost'
p=HTTPPasswordMgrWithDefaultRealm()
p.add_password(None,url,username,password)  #添加用户名和密码,建立处理验证的Handle
auth_handler=HTTPBasicAuthHandler(p)
opener=build_opener(auth_handler) #构建opener,它在发送请求时就相当于验证成功

try:
    result=opener.open(url)  #利用Opener的open方法打开链接,完成验证,获取的结果是验证后的页面源码内容
    html=result.read().decode('utf-8')
    print(html)
except URLError as e:
    print(e.reason)

Q:将url=‘http://localhost:5000’,运行结果是:目标计算机积极拒绝,无法连接。但去掉5000能出结果,但localhost的界面本就不需要验证。

2.ProxyHandler类搭建代理
from urllib.error import URLError
from urllib.request import ProxyHandler,build_opener

proxy_handler=ProxyHandler({ #该Handler的参数是字典,键名是协议类型,键值是代理链接
    'http':'http://127.0.0.1:9743', #在本地搭建了一个代理,运行在9743端口
    })
opener=build_opener(proxy_handler) #构造一个Opener
try:
    response=opener.open('https://python.org')
    print(response.read().decode('utf-8'))
except URLError as e:
    print(e.reason)
3.Cookies

获取网站上的Cookies

'''获取网站上的Cookies'''
import http.cookiejar,urllib.request

cookie=http.cookiejar.CookieJar()  #声明一个CookJar类对象
handler=urllib.request.HTTPCookieProcessor(cookie)  #构建一个Handler
opener=urllib.request.build_opener(handler)  #构建一个Opener
response=opener.open('http://www.baidu.com') #执行open()函数
for item in cookie:
    print(item.name+"="+item.value)

将Cookies保存成文件格式

'''以文件形式保存Cookies'''
import http.cookiejar,urllib.request

filename='cookies.txt'  #生成的文件名
cookie=http.cookiejar.MozillaCookieJar(filename)
'''MozillaCookieJar是CookieJar的子类,可处理Cookies和文件相关的操作(存取),
将Cookies保存成Mozilla浏览器的Cookies格式'''
cookie=http.cookiejar.LWPCookieJar(filename)
'''LWPCookieJar存取Cookies,将其保存为libwww-perl(LWP)格式的Cookies文件'''
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)

读取利用Cookies文件

'''读取利用Cookies文件'''
import http.cookiejar,urllib.request

cookie=http.cookiejar.LWPCookieJar()
cookie.load('cookies.txt',ignore_discard=True,ignore_expires=True) #load方法读取本地文件
handler=urllib.request.HTTPCookieProcessor(cookie)  #构建Handler
opener=urllib.request.build_opener(handler)   #构建Opener
response=opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))  #输出网页的源代码

官方文档:https://docs.python.org/3/library/urllib.request.html#basehandler-objects

本文为《Python3网络爬虫开发与实战》学习笔记。

二、error模块

urllib的error模块定义了由request模块产生的异常,若遇到问题,request模块便会抛出error模块中定义的异常。

(一)URLError类

error异常模块的基类,request模块产生的异常都可通过捕获这个类来处理。
reason属性:返回错误的原因。
例:访问一个不存在的页面捕获异常

from urllib import request,error
try:
    response=request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:   #捕获URLEorror异常,避免程序异常终止
    print(e.reason)
else:
    print("Request Successfully")

可先捕获子类,若不是子类错误再捕获父类错误:

from urllib import request,error
try:
    response=request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:   #先捕获子类的错误
    print(e.reason,e.code,e.headers,sep='\n')
except error.URLError as e:    #若不是URLError类错误,再捕获父类的错误
    print(e.reason)
else:                          #处理正常的逻辑
    print("Request Successfully")

reason属性的结果是socket.timeout类,可用isinstance()方法来判断它的类型,做更详细的异常判断:

import socket,urllib.request,urllib.error

try:
    response=urllib.request.urlopen('https://www.baidu.com',timeout=0.01)
except urllib.error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason,socket.timeout):  #isinstance方法做更详细的异常判断
        print('TIME OUT')

三、parse模块

它定义了处理URL的标准接口,例如实现URL各部分的抽取、合并以及链接转换。

1.urlparse()方法

可实现URL的识别和分段(按特定的分隔符实现解析):

from urllib.parse import urlparse
#urlparse()方法进行URL解析,输出解析结果类型和结果
result=urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result),result)

输出:

<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

返回结果为ParseResult类型的对象,含6部分:

  • scheme:协议(://前的部分)
  • netloc:域名(第一个/符号前面部分)
  • path:访问路径(分号;前面)
  • params:参数(分号;后面)
  • query:查询条件(问号?后面,如:id=5),多用于GET类型的URL
  • fragment:锚点(#后面),用于直接定位页面内部的下拉位置
    ParseResult类型的对象实际上是一个元组,可通过顺序索引或属性名来获取:
from urllib.parse import urlparse
#urlparse()方法进行URL解析,输出解析结果类型和结果
result=urlparse('https://www.baidu.com/index.html;user?id=5#comment')
print(type(result),result)
print(result.scheme,result[0],result.netloc,result[1],sep='\n') #属性名、顺序索引获取

标准的链接格式:
scheme://netloc/path;params?query#fragment
urlparse()方法的API用法:
urllib.parse.urlparse(urlstring,scheme=’’,allow_fragments=True)

  • urlstring:必填,待解析的URL。
  • scheme:默认的协议(如http或https),若一链接没带协议信息,会将这个作为默认的协议;但只在链接中没带协议信息时才生效。
  • allow_fragments:是否忽略fragment,若设置为False,Fragment会被忽略,它会被解析为path、parameters或query的一部分。
    粒:若在链接中省略协议:
from urllib.parse import urlparse
#urlparse()方法进行URL解析,输出解析结果类型和结果
result=urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https')
print(type(result),result)

2.urlunparse()方法

urlparse()的对立方法,它接受的参数为可迭代对象,但长度必须是6,否则会抛出参数不足或过多的问题。
例:构造一个URL:

from urllib.parse import urlunparse
data=['http','www.baidu.com','index.html','user','a=6','comment']
#data可为元组、列表等类型,或其他特定的数据结构
print(urlunparse(data))

3.urlsplit()方法

类似于urlparse()方法,但它不单独解析params部分(或合并到path中),只返回5个结果

from urllib.parse import urlsplit
result=urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
print(result)
print(result.scheme,result[0])  #通过属性、索引获取值

其返回结果是SplitResult类型,也是一个元组类型,可通过索引和属性来获取值。

4.urlunsplit()方法

与urlunparse()类似,唯一区别是长度必须是5.

from urllib.parse import urlsplit
data=['http','www.baidu.com','index.html','a=6','comment']
#data可为元组、列表等类型,或其他特定的数据结构
print(urlunsplit(data))

5.urljoin()方法

合成链接,但对长度和链接的每部分的清晰度没有严格要求。可提供一个base_url作为第一个参数,将新的链接作为第二个参数。该方法会分析base_url的scheme、netloc、path这三个内容(其他部分不起作用),对新链接缺失的部分进行补充,返回结果。

from urllib.parse import urljoin

print(urljoin('http://www.baidu.com','FAQ.html'))
print(urljoin('http://www.baidu.com','https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html','https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html','https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com/wd=abc','https://cuiqingcai.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'))

6.urlencode()方法

有助于构造GET请求参数。

from urllib.parse import urlencode

params={  #用字典将参数表示出来
    'name':'germey',
    'age':22
    }
base_url='http://www.baidu.com?'
url=base_url+urlencode(params)  #调用urlencode()方法将其序列化为GET请求
print(url)

7.parse_qs()方法

反序列化,将一串GET请求参数转回字典。

from urllib.parse import parse_qs
query='name=germey&age=22'
print(parse_qs(query))

输出:

{'name': ['germey'], 'age': ['22']}

8.parse_qsl()方法

用法同上一样,将参数转化成元组组成的列表。

9.quote()方法

URL中有中文参数时,会乱码,用此可将内容转化成URL编码的格式。

from urllib.parse import quote
from urllib.parse import unquote
keyword='壁纸'
url='https://www.baidu.com/s?wd='+quote(keyword) #编码
print(url)
print(unquote(url))  #解码

输出:

https://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8
https://www.baidu.com/s?wd=壁纸

10.unquote()方法

quote()的对立方法,可进行URL解码。(见上)

四、robotparser模块

该模块可用于实现Robots协议的分析。

(一)Robots协议

(爬虫协议、机器人协议),全名叫网络爬虫排除标准(Robots Exclusion Protocol),它告诉爬虫和搜索引擎哪些页面可以抓取,哪些页面不可以抓取。它通常是一个叫做robots.txt的文本文件,放在网站的根目录下。
爬虫访问一个站点,会首先检查站点根目录是否存在robot.txt文件,有,根据其定义的范围来爬取;否则,访问所有可直接访问的页面。(P120)

(二)爬虫名称

在这里插入图片描述

(三)robotparser模块

RobotFileParser类
根据某网站的robots.txt文件,判断一个爬虫是否有权限爬取这个网页。

urllib.robotparser.RobotFileParser(url='') #可在构造方法里传入robots.txt的链接

常用方法:

  • set_url():设置robots.txt文件的链接。
  • read():读取robots.txt文件并进行分析。执行读取分析操作,不返回任何内容,但必须调用。
  • parse():解析robots.txt文件,传入参数是robots.txt某些行的内容,按robots.txt的语法规则解析。
  • can_fetch(User-agent,URL):判定搜索引擎是否可以抓取这个URL,返回True或False。
  • mtime():返回上次抓取和分析robots.txt的时间,用于定期检查抓取最新的robots.txt。
  • modified():将当前时间设置为上次抓取和分析robots.txt的时间,用于长时间抓取。
    使用实例:
from urllib.robotparser import RobotFileParser

rp=RobotFileParser()  #创建RobotFileParser对象
#rp=RobotFileParser(url='http://www.jianshu.com/robot.txt)
rp.set_url('http://www.jianshu.com/robot.txt')  #设置robots.txt链接
rp.read() #不能缺省
print(rp.can_fetch('*','http://www.jianshu.com/p/b67554025d7d')) #判断网页是否可以抓取,'*'表示适用于所有爬虫?
print(rp.can_fetch('*','http://www.jianshu.com/search?q=python&page=1&type=collections'))

也可使用parse()方法来执行读取和分析:

from urllib.request import urlopen

rp=RobotFileParser()  #创建RobotFileParser对象
rp.parse(urlopen('http://www.jianshu.com/robot.txt').read().decode('utf-8').split('\n')))
print(rp.can_fetch('*','http://www.jianshu.com/p/b67554025d7d')) #判断网页是否可以抓取,'*'表示适用于所有爬虫?
print(rp.can_fetch('*','http://www.jianshu.com/search?q=python&page=1&type=collections'))

(运行结果为Forbidden)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值