以下是一些常见的用法:
1. 发送HTTP请求:
import urllib.request
url = 'https://www.example.com'
response = urllib.request.urlopen(url)
# 读取响应内容
html_content = response.read()
print(html_content.decode('utf-8'))
2. 使用urllib.parse解析URL:
from urllib.parse import urlparse
url = 'https://www.example.com/path/page?query=value'
parsed_url = urlparse(url)
print('Scheme:', parsed_url.scheme)
print('Netloc:', parsed_url.netloc)
print('Path:', parsed_url.path)
print('Query:', parsed_url.query)
3. 发送带参数的GET请求:
from urllib.parse import urlencode
base_url = 'https://www.example.com/search'
query_params = {'q': 'python', 'page': 1}
url = f'{base_url}?{urlencode(query_params)}'
response = urllib.request.urlopen(url)
html_content = response.read()
print(html_content.decode('utf-8'))
4. 发送POST请求:
import urllib.request
import urllib.parse
url = 'https://www.example.com/post_endpoint'
data = {'key1': 'value1', 'key2': 'value2'}
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
result = response.read()
print(result.decode('utf-8'))
这只是 urllib 的一些基本用法。对于更复杂的HTTP请求和处理,通常建议使用更高级的库,如 requests。
转载请注明出处:http://www.zyzy.cn/article/detail/13294/Python3