本文主要是介绍Urllib库及其常用的四个模块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 1. 什么是Urllib
- 2. Urllib库的4个核心模块
- 2.1 request
- 2.2 error
- 2.3 parse
- 2.4 robotparser
1. 什么是Urllib
urllib
是 Python 标准库中的一个模块,用于处理 URL 及其相关操作。它提供了一组用于打开和读取 URL 的功能,支持 HTTP、HTTPS、FTP 等协议。
2. Urllib库的4个核心模块
2.1 request
urllib.request
是 Python 标准库中的一个子模块,用于打开和读取 URL。它提供了一组用于发送 HTTP 请求的功能,包括 GET 和 POST 请求。以下是一些常见的用法示例:
发送GET请求:
import urllib.requestresponse = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))
发送POST请求:
import urllib.request# 请求网址
url = "https://www.spiderbuf.cn/playground/e01/login"# 请求体数据
data = {"user_name": "admin","password": "123456",
}# 请求头
headers = {"User-Agent": " Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
}# 将数据编码为 URL 编码格式,并转换为字节数据,以便在 POST 请求中发送
encoded_data = urllib.parse.urlencode(data).encode("utf-8")# 创建一个 Request 对象,包含 URL、编码后的数据、请求头和请求方法(POST)
request = urllib.request.Request(url, data=encoded_data, headers=headers, method="POST")# 发送请求并获取响应
response = urllib.request.urlopen(request)# 打印响应内容
print(response.read().decode("utf-8"))
拓展一下,urllib.request.urlopen
中的context
参数:
# 在发送请求时,可以额外添加 context 参数
context = ssl._create_unverified_context()
response = urllib.request.urlopen(req, context=context)
context=ssl._create_unverified_context()
这行代码的确意味着客户端在进行 HTTPS 请求时不会验证服务器的 SSL 证书的真实性。这在开发和测试环境中可能有用,但在生产环境中是不推荐的,因为它会使你的请求容易受到中间人攻击(MITM)。
urllib.request.urlopen
中的context
参数有什么用?
context
参数用于指定 SSL 上下文,以便控制 HTTPS 请求的安全设置。具体来说,context
参数允许你自定义 SSL/TLS 设置,例如禁用证书验证、设置证书文件等。简单介绍一下什么是
SSL/TLS
:
SSL
:一种用于保护互联网连接的标准技术,保护方法是对在网站和浏览器(或两个服务器之间)之间发送的数据进行加密。它能防止黑客查看或窃取传输的任何信息,包括个人或财务数据。关于它的应用最直观的就是HTTPS
,HTTPS
是在HTTP
上应用SSL
来保障HTTP
的安全性,对HTTPS
可以简单理解为HTTPS
=HTTP
+SSL
。
TLS
:是SSL的经过更新的、更安全的版本。
SSL
证书:是一种遵循SSL协议的数字证书,包含拥有者的公钥及相关身份信息,由受信任的数字证书颁发机构(CA)颁发。SSL证书采用SSL协议进行通信,具有服务器身份验证和数据传输加密功能,用于保证设备内的各服务间,以及设备与外部通信的安全性,防止通信数据在传输过程被篡改造成安全风险,提升系统的安全性。数字证书可以说是网络上的安全护照或身份证,提供的是网络上的身份证明。
SSL
的工作原理,可参考文章:SSL的工作原理及详细的握手过程
2.2 error
urllib
库中的 error
模块用于处理在使用 urllib
进行网络请求时可能出现的各种错误和异常。该模块定义了一些异常类,这些异常类可以帮助我们捕获和处理不同类型的错误情况。
-
URLError
:-
这是一个通用的异常类,用于捕获由
urllib
引发的所有错误。它通常在无法连接到服务器或请求超时时引发。 -
示例:
import urllib.request import urllib.errortry:response = urllib.request.urlopen("https://non-existent.com") except urllib.error.URLError as e:print(f"URL Error: {e.reason}")# 运行结果 # URL Error: [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1000)
-
-
HTTPError
:-
这是
URLError
的子类,专门用于处理 HTTP 请求返回的错误状态码(如 404、500 等)。它不仅包含错误信息,还包含 HTTP 响应码和响应头。 -
示例:
import urllib.request import urllib.errortry:response = urllib.request.urlopen("https://example.com/nonexistentpage") except urllib.error.HTTPError as e:print(f"HTTP Error: {e.code} - {e.reason} - {e.headers}")# 运行结果 # HTTP Error: 404 - Not Found - Accept-Ranges: bytes # Age: 516948 # Cache-Control: max-age=604800 # Content-Type: text/html; charset=UTF-8 # Date: Sun, 25 Aug 2024 14:47:42 GMT # Expires: Sun, 01 Sep 2024 14:47:42 GMT # Last-Modified: Mon, 19 Aug 2024 15:11:54 GMT # Server: ECAcc (sac/2574) # Vary: Accept-Encoding # X-Cache: 404-HIT # Content-Length: 1256 # Connection: close
-
-
ContentTooShortError
:-
当读取的内容比预期的要短时引发此异常。通常在下载文件时使用。
-
示例:
import urllib.request import urllib.errortry:response = urllib.request.urlopen("https://example.com/largefile")content = response.read()if len(content) < expected_length:raise urllib.error.ContentTooShortError("Content too short", content) except urllib.error.ContentTooShortError as e:print(f"Content Too Short Error: {e.reason}")
-
2.3 parse
urllib
库的 parse
模块提供了一些用于解析 URL 和处理 URL 编码的函数。
from urllib.parse import urlparse, urlunparse, urljoin, urlencode, quote, unquote# 解析 URL
url = "https://www.example.com/path;params?query=arg#frag"
parsed_url = urlparse(url)
print(parsed_url.netloc)
# 运行结果
# ParseResult(scheme='https', netloc='www.example.com', path='/path', params='params', query='query=arg', fragment='frag')# 组合 URL
url_components = ("https", "www.example.com", "/path", "params", "query=arg", "frag")
combined_url = urlunparse(url_components)
print(combined_url)
# 运行结果
# https://www.example.com/path;params?query=arg#frag# 组合基 URL 和相对 URL
base_url = "https://www.example.com/path/"
relative_url = "subpath/file.html"
full_url = urljoin(base_url, relative_url)
print(full_url)
# 运行结果
# https://www.example.com/path/subpath/file.html# URL 编码
params = {"name": "John Doe", "age": 30}
query_string = urlencode(params)
print(query_string)
# 运行结果
# name=John+Doe&age=30# URL 编码和解码
original_string = "Hello World!"
encoded_string = quote(original_string)
decoded_string = unquote(encoded_string)
print(encoded_string)
print(decoded_string)
# 运行结果
# Hello%20World%21
# Hello World!
2.4 robotparser
urllib
库的 robotparser
模块(在 Python 3 中被重命名为 urllib.robotparser
)用于解析 robots.txt
文件。robots.txt
文件是网站管理员用来控制搜索引擎爬虫访问其网站的文件。
from urllib.robotparser import RobotFileParser# 创建 RobotFileParser 对象
rp = RobotFileParser()# 设置 robots.txt 文件的 URL
rp.set_url("https://fanyi.baidu.com/mtpe-individual/multimodal#/")# 读取和解析 robots.txt 文件
rp.read()# 检查某个 URL 是否允许被爬取
url = "https://fanyi.baidu.com/mtpe-individual/multimodal#/"
user_agent = "*"
is_allowed = rp.can_fetch(user_agent, url)
print(f"URL {url} is allowed to be fetched: {is_allowed}")
# 运行结果
# URL https://fanyi.baidu.com/mtpe-individual/multimodal#/ is allowed to be fetched: True
这里注意,我们需要执行完 set_url
和 read()
方法之后,can_fetch
方法返回的结果才是有效的。调用 rp.read()
方法后,RobotFileParser
对象会从指定的 URL 下载并解析 robots.txt
文件。这个过程会将文件中的规则加载到内存中,以便后续的访问控制检查。
这篇关于Urllib库及其常用的四个模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!