URL 处理 Python 模块 (urllib)
pythonserver side programmingprogramming更新于 2025/6/27 12:28:17
Python 语言广泛用于 Web 编程。当我们浏览网站时,我们使用网址,也称为 URL 或统一资源定位器。Python 具有内置材料,可以处理对 URL 的调用以及传递访问 URL 的结果。在本文中,我们将看到一个名为 urllib 的模块。我们还将看到此模块中存在的各种函数,这些函数有助于从 URL 获取结果。
安装 urllib
要在 python 环境中安装 urllib,我们使用以下命令使用 pip。
pip install urllib
运行上述代码得到以下结果 −
打开 URL
request.urlopen 方法用于访问 URL 并将其内容提取到 python 环境。
示例
import urllib.request
address = urllib.request.urlopen('https://www.tutorialspoint.com/')
print(address.read())
输出
运行上述代码得到以下结果 −
b'<!DOCTYPE html>\r\n<!--[if IE 8]><html class="ie ie8"> <![endif]-->\r\n<!--[if IE 9]><html class…….. …………… ………………. new Date());\r\ngtag(\'config\', \'UA-232293-6\');\r\n</script>\r\n</body>\r\n</html>\r\n' -->
urllib.parse
我们可以解析 URL 来检查它是否有效。我们还可以将查询字符串传递给搜索选项。可以检查响应的有效性,如果响应有效,我们可以打印整个响应。
示例
import urllib.request
import urllib.parse
url='https://tutorialspoint.com'
values= {'q':'python'}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # data should be bytes
print(data)
req = urllib.request.Request(url, data)
resp = urllib.request.urlopen(req)
print(resp)
respData = resp.read()
print(respData)
输出
运行上述代码得到以下结果 −
b'q=python' <http.client.HTTPResponse object at 0x00000195BF706850> b'<!DOCTYPE html>\r\n<!--[if IE 8]><html class="ie ie8"> <![endif]………… ………………… \r\n</script>\r\n</body>\r\n</html<\r\n' -->
urllib.parse.urlsplit
urlsplit 可用于接收 URL,然后将其拆分为可用于进一步数据操作的部分。例如,如果我们想以编程方式判断 URL 是否经过 SSL 认证,那么我们应用 urlsplit 并获取方案值来决定。在下面的示例中,我们检查提供的 URL 的不同部分。X
输出
import urllib.parse url='https://tutorialspoint.com/python' value = urllib.parse.urlsplit(url) print(value)
运行上述代码得到以下结果 −
SplitResult(scheme='https', netloc='tutorialspoint.com', path='/python', query='', fragment='')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

