龙空技术网

Python3中的HTTP请求库——urllib

自由坦荡的湖泊AI 57

前言:

现在姐妹们对“python urllib urlencode”可能比较注重,小伙伴们都需要分析一些“python urllib urlencode”的相关知识。那么小编也在网络上汇集了一些关于“python urllib urlencode””的相关知识,希望咱们能喜欢,咱们一起来学习一下吧!

urllib 是 Python3 中自带的 HTTP 请求库,可以用于打开和读取 URL,解析 URL,处理异常,以及模拟浏览器的请求头等功能。urllib 包含四个模块,分别是:

urllib.request - 用于打开和读取 URL,支持 GET 和 POST 方法,以及添加请求头等。urllib.error - 用于处理 urllib.request 抛出的异常,如 HTTPError, URLError 等。urllib.parse - 用于解析 URL,包括编码和解码,拼接和分割等。urllib.robotparser - 用于解析 robots.txt 文件,判断哪些内容可以抓取,哪些不可以。

urllib 的基本用法是使用 urllib.request.urlopen 函数来打开一个 URL,返回一个类文件对象,可以使用 read, readline, readlines 等方法来读取网页内容。例如:

from urllib.request import urlopenmyURL = urlopen(";)print(myURL.read().decode("utf-8"))

如果要发送数据或者添加请求头,可以使用 urllib.request.Request 类来构造一个请求对象,然后传给 urlopen 函数。例如:

from urllib.request import Request, urlopenfrom urllib.parse import urlencodeurl = ";data = bytes(urlencode({"name": "WenAn"}), encoding="utf-8")headers = {"User-Agent": "Mozilla/5.0"}request = Request(url, data=data, headers=headers, method="POST")response = urlopen(request)print(response.read().decode("utf-8"))

urllib.parse 模块提供了一些函数来处理 URL,如 quote, unquote, urlencode, parse_qs, urlparse 等。例如:

from urllib.parse import quote, unquote, urlencode, parse_qs, urlparseurl = ";print(quote(url)) # 编码print(unquote(quote(url))) # 解码print(urlencode({"name": "WenAn"})) # 将字典转换为查询字符串print(parse_qs(urlencode({"name": "WenAn"}))) # 将查询字符串转换为字典print(urlparse(url)) # 将 URL 分割为六个部分

urllib.error 模块提供了一些异常类来处理 urllib.request 抛出的错误,如 HTTPError, URLError, ContentTooShortError 等。例如:

from urllib.request import urlopenfrom urllib.error import HTTPError, URLErrortry:    response = urlopen(";)except HTTPError as e:    print(e.code, e.reason, e.headers, sep="\n")except URLError as e:    print(e.reason)else:    print("Request Successfully")

urllib.robotparser 模块提供了一个 RobotFileParser 类来解析 robots.txt 文件,判断哪些内容可以抓取,哪些不可以。例如:

from urllib.robotparser import RobotFileParserrp = RobotFileParser()rp.set_url(";)rp.read()print(rp.can_fetch("*", ";)) # Trueprint(rp.can_fetch("*", ";)) # False

标签: #python urllib urlencode