Python 爬虫库 urllib 使用详解!

2023-02-1218:12:56后端程序开发Comments721 views字数 9683阅读模式
Python 爬虫库 urllib 使用详解!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

来源:海豚数据科学实验室文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

 文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

一、Python urllib库文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

Python urllib 库用于操作网页 URL,并对网页的内容进行抓取处理。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

Python3 的 urllib。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib 包 包含以下几个模块:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

  • urllib.request - 打开和读取 URL。
  • urllib.error - 包含 urllib.request 抛出的异常。
  • urllib.parse - 解析 URL。
  • urllib.robotparser - 解析 robots.txt 文件。

需要用的就是每个模块的内置方法和函数。大概方法如下图:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

Python 爬虫库 urllib 使用详解!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

二、urllib.request模块文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
urllib.request 定义了一些打开 URL 的函数和类,包含授权验证、重定向、浏览器 cookies等。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.request 可以模拟浏览器的一个请求发起过程。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

这里主要介绍两个常用方法,urlopen和Request。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

1. urlopen函数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
语法格式如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
  • url:url 地址。
  • data:发送到服务器的其他数据对象,默认为 None。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
  • timeout:设置访问超时时间。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
  • cafile 和 capath:cafile 为 CA 证书, capath 为 CA 证书的路径,使用 HTTPS 需要用到。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
  • cadefault:已经被弃用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
  • context:ssl.SSLContext类型,用来指定 SSL 设置。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

import urllib.request
#导入urllib.request模块
url=urllib.request.urlopen("https://www.baidu.com")
#打开读取baidu信息
print(url.read().decode('utf-8'))
#read获取所有信息,并decode()命令将网页的信息进行解码
运行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="
html{color:#000;overflow-y:scroll;overflow:-moz-scrollbars}                     
body,button,input,select,textarea{font-size:12px;font-family:Arial,sans-serif}  
h1,h2,h3,h4,h5,h6{font-size:100%}                                               
em{font-style:normal}                                                           
small{font-size:12px}                                                           
ol,ul{list-style:none}                                                          
a{text-decoration:none}                                                         
a:hover{text-decoration:underline}                                              
legend{color:#000}                                                              
fieldset,img{border:0}                                                          
button,input,select,textarea{font-size:100%} 
...
response对象是http.client. HTTPResponse类型,主要包含 read、readinto、getheader、getheaders、fileno 等方法,以及 msg、version、status、reason、debuglevel、closed 等属性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

常用方法:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

  • read():是读取整个网页内容,也可以指定读取的长度,如read(300)。获取到的是二进制的乱码,所以需要用到decode()命令将网页的信息进行解码。
  • readline() - 读取文件的一行内容。
  • readlines() - 读取文件的全部内容,它会把读取的内容赋值给一个列表变量。
  • info():返回HTTPMessage对象,表示远程服务器返回的头信息。
  • getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到。
  • geturl():返回请求的url。

2、Request类文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

我们抓取网页一般需要对 headers(网页头信息)进行模拟,否则网页很容易判定程序为爬虫,从而禁止访问。这时候需要使用到 urllib.request.Request 类:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
  • url:url 地址。
  • data:发送到服务器的其他数据对象,默认为 None。
  • headers:HTTP 请求的头部信息,字典格式。
  • origin_req_host:请求的主机地址,IP 或域名。
  • unverifiable:很少用整个参数,用于设置网页是否需要验证,默认是False。。
  • method:请求方法, 如 GET、POST、DELETE、PUT等。

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

import urllib.request
#导入模块
url = "https://www.baidu.com"
#网页连接
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"
}
#定义headers,模拟浏览器访问
req = urllib.request.Request(url=url,headers=headers)
#模拟浏览器发送,访问网页
response = urllib.request.urlopen(req)
#获取页面信息
print(response.read().decode("utf-8"))
三、urllib.error模块文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
urllib.error 模块为 urllib.request 所引发的异常定义了异常类,基础异常类是 URLError。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.error 包含了两个方法,URLError 和 HTTPError。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

URLError 是 OSError 的一个子类,用于处理程序在遇到问题时会引发此异常(或其派生的异常),包含的属性 reason 为引发异常的原因。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

HTTPError 是 URLError 的一个子类,用于处理特殊 HTTP 错误例如作为认证请求的时候,包含的属性 code 为 HTTP 的状态码, reason 为引发异常的原因,headers 为导致 HTTPError 的特定 HTTP 请求的 HTTP 响应头。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

区别:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

  • URLError封装的错误信息一般是由网络引起的,包括url错误。
  • HTTPError封装的错误信息一般是服务器返回了错误状态码。

关系:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

  • URLError是OSERROR的子类,HTTPError是URLError的子类。

1. URLError 示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


from urllib import request
from urllib import error

if __name__ == "__main__":
    #一个不存在的连接
    url = "http://www.baiiiduuuu.com/"
    req = request.Request(url)
    try:
        response = request.urlopen(req)
        html = response.read().decode('utf-8')
        print(html)
    except error.URLError as e:
        print(e.reason)
返回结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
[Errno -2] Name or service not known
reason:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

此错误的原因。它可以是一个消息字符串或另一个异常实例。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

2. HTTPError示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


from urllib import request
from urllib import error

if __name__ == "__main__":
    #网站服务器上不存在资源
    url = "http://www.baidu.com/no.html"
    req = request.Request(url)
    try:
        response = request.urlopen(req)
        html = response.read().decode('utf-8')
        print(html)
    except error.HTTPError as e:
        print(e.code)
返回结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
404
code文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

一个 HTTP 状态码,具体定义见 RFC 2616。这个数字的值对应于存放在文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

http.server.BaseHTTPRequestHandler.responses 代码字典中的某个值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

reason文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

这通常是一个解释本次错误原因的字符串。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

headers文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

导致 HTTPError 的特定 HTTP 请求的 HTTP 响应头。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

3. URLError和HTTPError混合使用文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

注意:由于HTTPError是URLError的子类,所以捕获的时候HTTPError要放在URLError的上面。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


from urllib import request
from urllib import error

if __name__ == "__main__":
    #网站服务器上不存在资源
    url = "http://www.baidu.com/no.html"
    req = request.Request(url)
    try:
        response = request.urlopen(req)
 #       html = response.read().decode('utf-8')
    except error.HTTPError as e:
        print(e.code)
    except error.URLError as e:
        print(e.code)
如果不用上面的方法,可以直接用判断的形式。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

from urllib import request
from urllib import error

if __name__ == "__main__":
    #网站服务器上不存在资源
    url = "http://www.baidu.com/no.html"
    req = request.Request(url)
    try:
        response = request.urlopen(req)
 #       html = response.read().decode('utf-8')
    except error.URLError as e:
        if hasattr(e, 'code'):
            print("HTTPError")
            print(e.code)
        elif hasattr(e, 'reason'):
            print("URLError")
            print(e.reason)
执行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
HTTPError
404
四、urllib.parse模块文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
模块定义的函数可分为两个主要门类: URL 解析和 URL 转码。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

4.1 URL 解析文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

4.1.1 urlparse()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.parse 用于解析 URL,格式如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
urlstring 为 字符串的 url 地址,scheme 为协议类型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

allow_fragments 参数为 false,则无法识别片段标识符。相反,它们被解析为路径,参数或查询组件的一部分,并 fragment 在返回值中设置为空字符串。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

标准链接格式为:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

scheme://netloc/path;params?query#fragment
对象中包含了六个元素,分别为:协议(scheme)、域名(netloc)、路径(path)、路径参数(params)、查询参数(query)、片段(fragment)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

from urllib.parse import urlparse

o = urlparse("https://docs.python.org/zh-cn/3/library/urllib.parse.html#module-urllib.parse")

print('scheme  :', o.scheme)
print('netloc  :', o.netloc)
print('path    :', o.path)
print('params  :', o.params)
print('query   :', o.query)
print('fragment:', o.fragment)
print('hostname:', o.hostname)
执行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

scheme  : https                                                                                                                                                                                          
netloc  : docs.python.org                                                       
path    : /zh-cn/3/library/urllib.parse.html                                    
params  :                                                                       
query   :                                                                       
fragment: module-urllib.parse                                                   
hostname: docs.python.org
以上还可以通过索引获取,如通过文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
print(o[0])
...
print(o[5])
4.1.2 urlunparse()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urlunparse()可以实现URL的构造。(构造URL)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urlunparse()接收一个是一个长度为6的可迭代对象,将URL的多个部分组合为一个URL。若可迭代对象长度不等于6,则抛出异常。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


from urllib.parse import urlunparse
url_compos = ['http','www.baidu.com','index.html','user= test','a=6','comment']
print(urlunparse(url_compos))
结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
http://www.baidu.com/index.html;user= test?a=6#comment
4.1.3 urlsplit()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urlsplit() 函数也能对 URL 进行拆分,所不同的是, urlsplit() 并不会把 路径参数(params) 从 路径(path) 中分离出来。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

当 URL 中路径部分包含多个参数时,使用 urlparse() 解析是有问题的,这时可以使用 urlsplit() 来解析.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

4.1.4 urlsplit()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urlunsplit()与 urlunparse()类似,(构造URL),传入对象必须是可迭代对象,且长度必须是5。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


from urllib.parse import urlunsplit
url_compos = ['http','www.baidu.com','index.html','user= test','a = 2']
print(urlunsplit(url_compos))urlunsplit()
结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
http://www.baidu.com/index.html?user= test#a = 2
4.1.5 urljoin()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

同样可以构造URL。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

传递一个基础链接,根据基础链接可以将某一个不完整的链接拼接为一个完整链接.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

注:连接两个参数的url, 将第二个参数中缺的部分用第一个参数的补齐,如果第二个有完整的路径,则以第二个为主。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

4.2 URL 转码文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

python中提供urllib.parse模块用来编码和解码,分别是urlencode()与unquote()。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

4.2.1 编码quote(string)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

URL 转码函数的功能是接收程序数据并通过对特殊字符进行转码并正确编码非 ASCII 文本来将其转为可以安全地用作 URL 组成部分的形式。它们还支持逆转此操作以便从作为 URL 组成部分的内容中重建原始数据,如果上述的 URL 解析函数还未覆盖此功能的话文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

语法:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.parse.quote(string, safe='/', encoding=None, errors=None)
使用 %xx 转义符替换 string 中的特殊字符。字母、数字和 '_.-~' 等字符一定不会被转码。在默认情况下,此函数只对 URL 的路径部分进行转码。可选的 safe 形参额外指定不应被转码的 ASCII 字符 --- 其默认值为 '/'。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

string 可以是 str 或 bytes 对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html



from urllib import parse

url = "http://www.baidu.com/s?wd={}"
words = "爬虫"

#quote()只能对字符串进行编码
query_string = parse.quote(words)
url = url.format(query_string)
print(url)
执行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
http://www.baidu.com/s?wd=%E7%88%AC%E8%99%AB
4.2.2 编码urlencode()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

quote()只能对字符串编码,而urlencode()可以对查询字符串进行编码。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


# 导入parse模块
from urllib import parse

#调用parse模块的urlencode()进行编码
query_string = {'wd':'爬虫'}
result = parse.urlencode(query_string)

# format函数格式化字符串,进行url拼接
url = 'http://www.baidu.com/s?{}'.format(result)
print(url)
结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
http://www.baidu.com/s?wd=%E7%88%AC%E8%99%AB
4.2.3 解码unquote(string)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

解码就是对编码后的url进行还原。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html


from urllib import parse
string = '%E7%88%AC%E8%99%AB'
result = parse.unquote(string)
print(result)
执行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
爬虫
五、urllib.robotparser模块文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

(在网络爬虫中基本不会用到,使用较少,仅作了解)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.robotparser 用于解析 robots.txt 文件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

robots.txt(统一小写)是一种存放于网站根目录下的 robots 协议,它通常用于告诉搜索引擎对网站的抓取规则。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

Robots协议也称作爬虫协议,机器人协议,网络爬虫排除协议,用来告诉爬虫哪些页面是可以爬取的,哪些页面是不可爬取的。它通常是一个robots.txt的文本文件,一般放在网站的根目录上。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

当爬虫访问一个站点的时候,会首先检查这个站点目录是否存在robots.txt文件,如果存在,搜索爬虫会根据其中定义的爬取范围进行爬取。如果没有找到这个文件,搜索爬虫会访问所有可直接访问的页面。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

urllib.robotparser 提供了 RobotFileParser 类,语法如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html

class urllib.robotparser.RobotFileParser(url='')
这个类提供了一些可以读取、解析 robots.txt 文件的方法:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
  • set_url(url) - 设置 robots.txt 文件的 URL。
  • read() - 读取 robots.txt URL 并将其输入解析器。
  • parse(lines) - 解析行参数。
  • can_fetch(useragent, url) - 如果允许 useragent 按照被解析 robots.txt 文件中的规则来获取 url 则返回 True。
  • mtime() -返回最近一次获取 robots.txt 文件的时间。这适用于需要定期检查 robots.txt 文件更新情况的长时间运行的网页爬虫。
  • modified() - 将最近一次获取 robots.txt 文件的时间设置为当前时间。
  • crawl_delay(useragent) -为指定的 useragent 从 robots.txt 返回 Crawl-delay 形参。如果此形参不存在或不适用于指定的 useragent 或者此形参的 robots.txt 条目存在语法错误,则返回 None。
  • request_rate(useragent) -以 named tuple RequestRate(requests, seconds) 的形式从 robots.txt 返回 Request-rate 形参的内容。如果此形参不存在或不适用于指定的 useragent 或者此形参的 robots.txt 条目存在语法错误,则返回 None。
  • site_maps() - 以 list() 的形式从 robots.txt 返回 Sitemap 形参的内容。如果此形参不存在或者此形参的 robots.txt 条目存在语法错误,则返回 None。
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/30857.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/30857.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定