Python urllib库
Python urllib库是Python标准库,提供了处理URL请求和响应的功能。它提供了一系列的模块,可以让用户访问URL,获取URL上的数据,发送HTTP请求,处理Cookies等。
使用方法
使用Python urllib库可以实现以下功能:
- 获取URL的响应:urllib.request.urlopen()
- 发送HTTP请求:urllib.request.Request()
- 处理Cookie:urllib.request.HTTPCookieProcessor()
- 设置HTTP头:urllib.request.build_opener()
- 解析URL:urllib.parse.urlparse()
示例
以下是使用Python urllib库发送HTTP请求的示例:
import urllib.request url = 'http://www.example.com/' # 设置HTTP头 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'} # 构建请求 request = urllib.request.Request(url, headers=headers) # 发送请求 response = urllib.request.urlopen(request)
以上示例中,使用urllib.request.Request()构建了一个请求,使用urllib.request.urlopen()发送了请求,获取了响应。