urllib 是一个 python 内置包,不需要额外安装即可使用,包里面包含了以下几个用来处理 url 的模块:
掌握以上四个模块,就能对网站进行简单的爬虫操作,下面我们逐个介绍。
urllib.request 模块定义了以下几个函数。
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
该函数主要用于模拟网站请求,返回一个 HTTPResponse 类型的对象。
urlopen 函数中参数定义
urlopen 函数返回类型
urlopen 函数请求返回一个 HTTPResponse 响应上下文,或者请求异常抛出 URLError 协议错误,一般有如下属性:
urlopen 函数的应用实例
# 创建一个 HTTP GET 请求,输出响应上下文
from urllib.request import urlopen
response = urlopen("http://www.python.org")
print(response.read()) # 创建一个 HTTP POST 请求,输出响应上下文
from urllib.request import urlopen
from urllib.parse import urlencode
data = {'kw' : 'python'}
data = bytes(urlencode(data), encoding = 'utf-8')
response = urlopen("https://fanyi.baidu.com/sug", data)
print(response.read().decode('unicode_escape'))# 创建一个 HTTP GET 请求,设置超时时间为0.1s
import urllib.request
import urllib.error
try:
response=urllib.request.urlopen('http://www.python.org',timeout=0.1)
print(response.read())
except urllib.error.URLError as e:
print(e.reason)urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
该函数主要用于构造一个 url,返回一个 urllib.request.Request 对象。
Request 函数返回类型
与 urlopen 函数请求返回一样,一般返回一个 HTTPResponse 响应上下文。
Request 函数的应用实例
# 采用 HTTP GET 请求的方法模拟谷歌浏览器访问网站,输出响应上下文
from urllib import request,parse
url = 'http://www.python.org'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
req = request.Request(url, headers = headers, method = 'GET')
response = request.urlopen(req)
print(response.read())# 采用 HTTP POST 请求的方法模拟谷歌浏览器访问网站,输出响应上下文
from urllib import request
from urllib import parse
url = 'https://fanyi.baidu.com/sug'
data = {'kw' : 'python'}
data = bytes(parse.urlencode(data), encoding = 'utf-8')
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
req = request.Request(url, data, headers, method = 'POST')
response = request.urlopen(req)
print(response.read().decode('unicode_escape'))# 创建一个 HTTP GET 请求,通过 add_header 添加一个 UserAgent
import urllib.request
import random
url = 'http://www.python.org'
headerUserAgentList = ['Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0']
randomHeaderUserAgent = random.choice(headerUserAgentList) # 随机选取一个 UserAgent
req = urllib.request.Request(url)
req.add_header('User-Agent', randomHeaderUserAgent) # 添加 UserAgent
response=urllib.request.urlopen(req)
print(req.get_header('User-agent'))
print(req.headers) # 打印请求的 header 信息urllib.error 模块定义了由 urllib.request 模块引发的异常,异常主要包含 URLError 和 HTTPError。
urllib.error.URLError 异常
URLError 类继承自 OSError 类,是 error 异常模块的基类,由request模块产生的异常都可以通过捕获这个类来处理。URLError 只有一个属性 reason,即返回错误的原因。
应用实例:
# 在请求连接时候捕获网址错误引发的异常
from urllib import request, error
try:
response = request.urlopen('https://www,baidu,com')
except error.URLError as e:
print(e.reason)urllib.error.HTTPError 异常
HTTPError 是 URLError 的子类,专门用来处理 HTTP 请求错误,比如认证请求失败,包含以下三个属性:
应用举例:
# 返回401未授权错误
from urllib import request,error
try:
response=request.urlopen('http://pythonscraping.com/pages/auth/login.php')
print(response.getcode())
except error.HTTPError as e:
print('1.错误原因:
%s
2.状态码:
%s
3.响应头信息:
%s' %(e.reason, e.code, e.headers))
except error.URLError as e:
print(e.reason)urllib.parse 模块定义了一个处理 url 的标准接口,用来实现 url 字符串的抽取、合并以及链接转换。该模块主要用到的函数如下。
urllib.parse.urlparse(urlstring, scheme=’’, allow_fragments=True)
用于实现 url 字符串的识别和分段,可以分为六个字符串,分别是 scheme (协议),netloc (域名),path (路径),params (参数),query (查询条件)和 fragment (锚点),其结构如下所示:“scheme://netloc/path;parameters?query#fragment”。实际上具体 url 某些字段可能会不存在,比如 “http://www.baidu.com” 只包含了协议和域名。
urlparse 函数中参数定义
urlparse 的返回类型
函数返回的是一个 urllib.parse.ParseResult 对象,获取解析出来的 url 六个字段。
urlparse 应用举例
# 解析并输出 url 中每个字段的字符串
import urllib
url = 'http://www.baidu.com/urllib.parse.html;python?kw=urllib.parse#module-urllib'
result = urllib.parse.urlparse(url)
print(result)
print(result.scheme, result.netloc, result.path, result.params, result.query, result.fragment, sep = '
')urllib.parse.urlunparse(parts)
与 urlparse 相反,通过列表或者元祖的形式将分段的字符串组合成一个完整的 url 字符串。
urlunparse 函数中参数定义
urlunparse 的返回类型
urlunparse 函数返回一个构造好的 url 字符串。
应用举例:
# 通过 data 列表或元组构造一个 url 并输出
import urllib
dataList = ['http', 'www.baidu.com', '/urllib.parse.html', 'python', 'kw=urllib.parse', 'modul-urllib'] # 六个字符串都必须填写,否则会出现 ValueError 错误,如果某一字符串不存在则填入空字符
dataTuple = ('http', 'www.baidu.com', '/urllib.parse.html', '', 'kw=urllib.parse', 'modul-urllib') # 六个字符串都必须填写,否则会出现 ValueError 错误,如果某一字符串不存在则填入空字符
urlList = urllib.parse.urlunparse(dataList)
urlTuple = urllib.parse.urlunparse(dataTuple)
print('1.urlList:%s
2.urlTuple:%s' % (urlList, urlTuple))urllib.parse.urlsplit(urlstring, scheme=’’, allow_fragments=True)
与 urlparse 函数类似,但它只返回 url 字符串的5个字段,把 params 合并到 path 中。
urlsplit 应用举例
# 解析并输出 url 中每个字段的字符串,params 会合并到 path 中。
import urllib
url = 'http://www.baidu.com/urllib.parse.html;python?kw=urllib.parse#modul-urllib'
result = urllib.parse.urlsplit(url)
print(result)
print(result.scheme, result.netloc, result.path, result.query, result.fragment, sep = '
')urllib.parse.urlunsplit(parts)
与 urlunparse 函数类似,它也是将 url 各部分字段组合完整的 url 字符串的方法,唯一的区别是列表或元组的长度必须是5个,因为它把 params 省略了。
urlunsplit 应用举例
# 通过 data 列表或元组构造一个 url 并输出
import urllib
dataList = ['http', 'www.baidu.com', '/urllib.parse.html;python', 'kw=urllib.parse', 'modul-urllib'] # 五个字符串都必须填写,否则会出现 ValueError 错误,如果某一字符串不存在则填入空字符
dataTuple = ('http', 'www.baidu.com', '/urllib.parse.html;python', 'kw=urllib.parse', 'modul-urllib') # 五个字符串都必须填写,否则会出现 ValueError 错误,如果某一字符串不存在则填入空字符
urlList = urllib.parse.urlunsplit(dataList)
urlTuple = urllib.parse.urlunsplit(dataTuple)
print('1.urlList:%s
2.urlTuple:%s' % (urlList, urlTuple))urllib.robotparser.RobotFileParser(url=’’) 类及其常用方法
应用举例
# 使用两种爬虫代理分别查看是否可以对 'http://www.baidu.com' 网站进行爬取
from urllib.robotparser import RobotFileParser
rp = RobotFileParser()
rp.set_url("http://www.baidu.com/robots.txt")
rp.read()
print(rp.can_fetch('Baiduspider', 'http://www.baidu.com'))
print(rp.can_fetch('*', 'http://www.baidu.com'))
| 留言与评论(共有 0 条评论) “” |