在 Python 中,urllib 模块提供了用于处理 URL 的工具。它包含了一些子模块,其中最常用的是 urllib.request、urllib.parse、urllib.error 和 urllib.robotparser。

1. urllib.request

urllib.request 模块用于打开和读取 URL。以下是一些基本的用法:

发送 HTTP 请求:
from urllib.request import urlopen

with urlopen('https://www.example.com') as response:
    html = response.read()
    print(html)

使用 Request 对象:
from urllib.request import Request, urlopen

url = 'https://www.example.com'
headers = {'User-Agent': 'Mozilla/5.0'}  # 添加请求头
req = Request(url, headers=headers)

with urlopen(req) as response:
    html = response.read()
    print(html)

2. urllib.parse

urllib.parse 模块用于解析和构建 URL。以下是一些基本的用法:

解析 URL:
from urllib.parse import urlparse

url = 'https://www.example.com/path/page?query=123'
parsed_url = urlparse(url)

print(f'Scheme: {parsed_url.scheme}')
print(f'Netloc: {parsed_url.netloc}')
print(f'Path: {parsed_url.path}')
print(f'Query: {parsed_url.query}')

构建 URL:
from urllib.parse import urlencode, urlunparse

params = {'param1': 'value1', 'param2': 'value2'}
encoded_params = urlencode(params)

url_parts = ('https', 'www.example.com', '/path', '', encoded_params, '')
full_url = urlunparse(url_parts)

print(full_url)

3. urllib.error

urllib.error 模块包含了一些与 URL 相关的错误类,例如 HTTPError 和 URLError。

4. urllib.robotparser

urllib.robotparser 模块用于解析 robots.txt 文件,该文件定义了哪些爬虫可以访问网站的哪些部分。

以上只是 urllib 模块的一些基本用法。在实际应用中,你可能需要处理更复杂的请求、异常处理、cookie 管理等。如果你的需求变得更加复杂,考虑使用第三方库,例如 requests,它提供了更多功能和更简单的接口。


转载请注明出处:http://www.zyzy.cn/article/detail/245/Python3