Python 3中的urllib模块可以用来处理URL,包括下载和上传文件、创建和读取cookie、访问Web API等。在本文中,我们将详细介绍urllib库中最常用的四个模块:urllib.request、urllib.parse、urllib.error和urllib.robotparser。
一、urllib.request模块
该模块提供了许多功能,如打开URL、读取其中的响应,以及设置请求头等。
打开URL 有两种方法打开URL,分别是使用urllib.request.urlopen()和 urllib.request.Request()。
1.1 使用urllib.request.urlopen()
可以使用urlopen()函数打开一个URL,如果给定了字符串参数,将尝试打开这个URL,并且返回一个 file-like 对象,在此对象上可以执行类似文件的操作。例如:
python
import urllib.request
response = urllib.request.urlopen(‘https://www.example.com/’)
print(response.read().decode(‘utf-8’))
此代码将在控制台输出从示例站点获取的HTML内容。
1.2 使用urllib.request.Request()
假设需要传递一些参数、HTTP头等信息,则可以使用Request()方法构造一个请求对象,然后再调用urlopen()发送请求。例如:
python
import urllib.request
req = urllib.request.Request(‘http://www.example.com/’, data=b’some_data’, headers={‘User-Agent’: ‘Mozilla/5.0’})
response = urllib.request.urlopen(req)
print(response.read().decode(‘utf-8’))
这里创建了一个请求对象,其中包含URL、数据(可
[Cannot read property ‘status’ of undefined]