[[Python]] URL 解析和转码模块。
解析
URL
from urllib.parse import urlparse
urlparse("http://docs.python.org:80/3/library/urllib.parse.html?highlight=params#url-parsing")
# 返回:ParseResult(scheme='http', netloc='docs.python.org:80', path='/3/library/urllib.parse.html', params='', query='highlight=params', fragment='url-parsing')
查询参数
- parse_qs():是以字段名和列表值组成的键值对以字典形式返回
- parse_qsl():是以字段名和值组成的元组以列表形式返回
转码
quote
使用 %xx 转义符替换 string 中的特殊字符。
from urllib.parse import quote
url = "https://immwind.com"quote(url) # 返回: https%3A//immwind.com'
# 默认情况下斜杆 “/” 不会被转码,可以通过指定 safe 参数进行转码quote("https://immwind.com", safe="") # 返回: 'https%3A%2F%2Fimmwind.com'