本文共 2437 字,大约阅读时间需要 8 分钟。
urlopen函数是urllib.request模块中最常用的工具,用于发送HTTP请求并获取网页内容。以下是使用urlopen的基本步骤:
import urllib.request# 示例网址url = r'http://example.com'# 使用urlopen函数获取页面数据response = urllib.request.urlopen(url)# response对象返回的页面数据类型为bytes,需decode转换为字符串page = response.read().decode('utf-8') HTTPResponse对象提供以下操作方法:
read(): 读取整个页面内容readline(): 逐行读取内容fileno(): 获取文件描述符close(): 关闭资源info(): 获取HTTP头信息getcode(): 获取HTTP状态码geturl(): 获取请求的URL为了实现更复杂的HTTP请求,urllib.request提供了Request对象。通过Request对象可以自定义headers、方法等参数:
import urllib.requestfrom urllib.parse import urlencode# 示例网址url = r'http://example.com/post.php'# 定义HTTP请求头headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.3978.99 Safari/537.36', 'Referer': 'https://www.example.com', 'Connection': 'keep-alive'}# 创建Request对象req = urllib.request.Request(url, headers=headers)#发送请求并获取响应response = urllib.request.urlopen(req)# 获取页面内容page = response.read().decode('utf-8') keep-alive要提交POST数据,urlopen函数的data参数可以传递字典数据,通过urlencode函数转换为URL查询字符串:
import urllib.requestfrom urllib.parse import urlencode# 示例网址url = r'http://example.com/form.php'# 定义请求数据data = { 'username': 'admin', 'password': '123456'}# URL编码处理encoded_data = urlencode(data).encode('utf-8')# 发送POST请求req = urllib.request.Request(url, data=encoded_data)# 获取响应response = urllib.request.urlopen(req)# 解码页面内容page = response.read().decode('utf-8') bytes类型提交,使用encode()方法进行转换urlencode函数编码处理在实际应用中,网络请求可能会遇到错误。我们可以通过try-except块来处理异常:
import urllib.requestfrom urllib.error import HTTPErrordef fetch_page(url): try: # 定义请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.3978.99 Safari/537.36', 'Referer': 'https://www.example.com' } # 创建Request对象 req = urllib.request.Request(url, headers=headers) # 获取HTTP响应 response = urllib.request.urlopen(req) # 获取页面内容 page = response.read().decode('utf-8') return page except HTTPError as e: print(f'HTTP错误:{e.code()} - {e.read().decode("utf-8")}') return None -捕获HTTP错误状态码,避免程序因为异常而
转载地址:http://tflfk.baihongyu.com/