urllib是Python标准库中的一个模块,它提供了一系列用于操作URL的功能requests是一个Python第三方库,由Kenneth Reitz创建,用于简化HTTP客户端的编程
urllib的定义urllib可以操作url,主要分为以下几个子模块:
urllib.request用于打开和读取URLs
urllib.error包含urllib.request引发的异常
urllib.parse用于解析URLs
urllib.robotparser用于解析robots.txt文件
urllib的特点urllib是Python标准库的一部分,因此不需要额外安装
支持多种网络协议,包括HTTP、HTTPS、FTP等
提供了简单易用的API,适合进行简单的网络请求操作
urllib的功能使用urllib.request.urlopen()函数可以轻松打开一个URL
支持发送GET、POST等HTTP请求
urllib.error模块可以捕获和处理网络请求过程中出现的异常
urllib.parse模块可以解析和构造URLs
urllib.robotparser模块可以帮助遵守网站的爬虫访问规则
urllib的代码示例以下是使用urllib模块进行网络请求的几个示例:
import urllib.request # 发送GET请求 with urllib.request.urlopen('http://www.example.com') as response: html = response.read() print(html.decode('utf-8')) import urllib.request import urllib.parse url = 'http://httpbin.org/post' values = {'key': 'value'} data = urllib.parse.urlencode(values) data = data.encode('utf-8') # data should be bytes req = urllib.request.Request(url, data=data, method='POST') with urllib.request.urlopen(req) as response: print(response.read().decode('utf-8')) import urllib.request import urllib.error try: response = urllib.request.urlopen('http://www.example.com/404') except urllib.error.HTTPError as e: print(f'HTTPError: {e.code} {e.reason}') except urllib.error.URLError as e: print(f'URLError: {e.reason}') from urllib.parse import urlparse result = urlparse('http://www.example.com/index.html;user?id=5#comment') print(result) # 输出:ParseResult(scheme='http', netloc='www.example.com', path='/index.html', params='user', query='id=5', fragment='comment') 以上示例展示了urllib库的一些基本用法,包括如何发送HTTP请求、如何处理请求异常以及如何解析URLs。由于urllib库功能丰富,这些示例只是冰山一角。
requests的定义
requests是基于urllib3,提供了一个更加用户友好的API来发送HTTP/1.1请求
requests的特点requests的API设计简洁直观,易于上手和使用
支持HTTP连接保持和连接池,支持SSL/TLS验证,支持国际化和本地化等
自动处理HTTP响应内容的编码问题
能够使用会话对象来跨请求保持某些参数,如cookies
requests支持插件,可以轻松扩展其功能
requests的功能requests的安装requests不是Python标准库的一部分,需要通过以下命令安装:pip install requests 
requests的代码示例以下是使用requests库进行网络请求的几个示例:
import requests response = requests.get('https://api.github.com/user', params={'username': 'example'}) print(response.json()) import requests data = {'key1': 'value1', 'key2': 'value2'} response = requests.post('http://httpbin.org/post', data=data) print(response.text) import requests s = requests.Session() s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') response = s.get("http://httpbin.org/cookies") print(response.text) import requests from requests.exceptions import HTTPError, ConnectionError, Timeout, RequestException try: response = requests.get('https://api.github.com', timeout=5) response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except ConnectionError as conn_err: print(f'Connection error occurred: {conn_err}') except Timeout as timeout_err: print(f'Timeout error occurred: {timeout_err}') except RequestException as req_err: print(f'Oh no, something bad happened: {req_err}') import requests files = {'file': open('report.xls', 'rb')} response = requests.post('http://httpbin.org/post', files=files) print(response.text) 这些示例展示了requests库的几个核心功能
requests库因其简洁和强大而成为Python中处理HTTP请求的常用库
urllib和requests的区别
urllib和requests都是Python中用于发送HTTP请求的库,但它们在API设计、易用性、功能性和社区支持等方面存在一些显著的区别
requests.exceptions模块来捕获和处理各种异常http.client)来优化urllib3,因此在性能上有所优化,尤其是在并发请求时以下是使用urllib和requests发送GET请求的简单示例对比:
使用urllib发送GET请求:
import urllib.request import urllib.error try: with urllib.request.urlopen('http://example.com') as response: data = response.read() print(data.decode('utf-8')) except urllib.error.HTTPError as e: print(f'HTTPError: {e.code} {e.reason}') except urllib.error.URLError as e: print(f'URLError: {e.reason}') 使用requests发送GET请求:
import requests response = requests.get('http://example.com') print(response.text) 使用
requests发送网络请求通常更加简洁明了
然而,由于urllib是Python标准库的一部分,因此在不允许安装第三方库的环境中,urllib可能是唯一的选择
