笔记-urllib-parse

1. 简介
模块官方解释
This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”
简单来说就是处理/解析URL的。
2. 解析函数
2.1. urllib.parse
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
函数用于将一个URL解析成六个部分,返回一个元组,URL的格式为:scheme://netloc/path;parameters?query#fragment;包含六个部分,元组中每一个元素都是一个字符串,可以为空,这六个部分均不能再被分割成更小的部分;
以下为返回的元组元素:

元素 编号 值 值不存在时默认值
scheme 0 请求 一定存在
netloc 1 网址 空字符串
path 2 分层路径 空字符串
params 3 参数 空字符串
query 4 查询组件 空字符串
fragment 5 标识符 空字符串
username 用户名 None
password 密码 None
hostname 主机名 None
port 端口号 None

典型使用:
import urllib.parse
o = urllib.parse.urlparse('https://blog.csdn.net/qq_41769259/article/details/79434494')
print(o)

2.2. parse_qs
urllib.parse.parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')
这个函数主要用于分析URL中query组件的参数,返回一个key-value对应的字典格式。
简单应用:
print(urllib.parse.parse_qs("FuncNo=9009001&username=1"))
输出:
{'FuncNo': ['9009001'], 'username': ['1']}

urllib.parse.parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding=’utf-8’, errors=’replace’)
这个函数和urllib.parse.parse_qs()作用一样,唯一的区别就是这个函数返回值是list形式;

2.3. urlunparse()
urllib.parse.urlunparse(parts)
Construct a URL from a tuple as returned by urlparse(). The parts argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent).
这个函数可以将urlparse()分解出来的元组组装成URL;
o = urllib.parse.urlparse('https://www.zhihu.com/question/50056807/answer/2235669')
print(o)
print(urllib.parse.urlunparse(o))
output:
ParseResult(scheme='https', netloc='www.zhihu.com', path='/question/50056807/answer/2235669', params='', query='', fragment='')
https://www.zhihu.com/question/50056807/answer/2235669
2.4. urlsplit()
urllib.parse.urlsplit(urlstring, scheme='', allow_fragments=True)
This is similar to urlparse(), but does not split the params from the URL. This should generally be used instead of urlparse() if the more recent URL syntax allowing parameters to be applied to each segment of the path portion of the URL (see RFC 2396) is wanted. A separate function is needed to separate the path segments and parameters. This function returns a 5-tuple: (addressing scheme, network location, path, query, fragment identifier).
这个函数和urlparse()功能类似,但是不会将param分离出来;相比urlparse()少一个param元素,返回的元组元素参照urlparse()的元组表。
2.5. urljoin()
urllib.parse.urljoin(base, url, allow_fragments=True)
将一个基址和一个相对地址组合成新的URL。
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
'http://www.cwi.nl/%7Eguido/FAQ.html'
值得注意的是如果被组合的地址是绝对地址,那么结果会不一样,在编程中应通过预处理尽量避免这种情况:
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
... '//www.python.org/%7Eguido')
'http://www.python.org/%7Eguido'

3. quote
The URL quoting functions focus on taking program data and making it safe for use as URL components by quoting special characters and appropriately encoding non-ASCII text. They also support reversing these operations to recreate the original data from the contents of a URL component if that task isn’t already covered by the URL parsing functions above.
这个模块的主要作用就是通过引入合适编码和特殊字符对URL进行安全重构,并且可以反向解析
3.1. quote()
urllib.parse.quote(string, safe='/', encoding=None, errors=None)
Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of URL. The optional safe parameter specifies additional ASCII characters that should not be quoted — its default value is '/'.
案例:
url="https://www.zhihu.com/question/50056807/answer/223566912"
print(urllib.parse.quote(url))
print(urllib.parse.quote(url,safe=":"))
输出:
https%3A//www.zhihu.com/question/50056807/answer/223566912
https:%2F%2Fwww.zhihu.com%2Fquestion%2F50056807%2Fanswer%2F223566912

3.2. quote_plus()
urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)
Like quote(), but also replace spaces by plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.
Example: quote_plus('/El Niño/') yields '%2FEl+Ni%C3%B1o%2F'.
这个函数和quote()相似,但是这个函数能把空格转成加号,并且safe的默认值为空
3.3. quote_from_bytes()
urllib.parse.quote_from_bytes(bytes, safe=’/’)
和quote()相似,但是接收的是字节而不是字符;

笔记-urllib-parse的更多相关文章

  1. python学习笔记——urllib库中的parse

    1 urllib.parse urllib 库中包含有如下内容 Package contents error parse request response robotparser 其中urllib.p ...

  2. 我与python3擦肩而过(三)—— 我去。。又是编码问题——urllib.parse.unquote

    记得初学python时就学的爬虫,经常遇到编码问题(其实在python3里面编码问题已经很少了...),用requests库就挺方便解决这些问题的.近来有共同学习python的程序员写了个电子书网站, ...

  3. urllib.parse

    1 url分解 import urllib.parse result = urllib.parse.urlparse('http://www.baidu.com') print(result) 结果为 ...

  4. urllib.parse.urlencode

    urllib.request.urlopen(url,data,timeout) 其中如果data被赋值,则请求的方式就会由get转为post,而post需要提供一些待处理的数据. 这些待处理的数据需 ...

  5. Python 的 urllib.parse 库解析 URL

      Python 中的 urllib.parse 模块提供了很多解析和组建 URL 的函数. 解析url urlparse() 函数可以将 URL 解析成 ParseResult 对象.对象中包含了六 ...

  6. python3中的urllib.parse的常用方法

    将URL按一定的格式进行拆分 使用 urllib.parse.urlparse将url分为6个部分,返回一个包含6个字符串项目的元组:协议.位置.路径.参数.查询.片段 参照官方地址:https:// ...

  7. python3 urllib.parse 常用函数

    1.获取url参数 urlparse from urllib import parse url = "https://docs.python.org/3.5/library/urllib.p ...

  8. urllib.parse.quote

    sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...

  9. URL组成成分及各部分作用简介及urllib.parse / uri

    URL的一般格式为(带方括号[]的为可选项): protocol :// hostname[:port] / path / [;parameters][?query]#fragment urllib. ...

  10. urllib.parse.parse_qsl 的一个小问题

    最近在使用urllib时发现的一个问题,记录一下. 首先请分别执行下面这两句代码: 1."你好".encode("utf8").decode("gbk ...

随机推荐

  1. Day2下午

    虽然成绩不太好,但有点进入状态了.期望200 实际160,忘记加判断了. T1 洗澡[问题描述]你是能看到第一题的friends 呢.——hja洗澡的地方,有一段括号序列,将一个括号修改一次需要1的代 ...

  2. HTML5 有哪些不同类型的存储?

    HTML 5 支持本地存储,在之前版本中是通过 Cookie 实现的.HTML5 本地存储速度快而且安全. 有两种不同的对象可用来存储数据: localStorage 适用于长期存储数据,浏览器关闭后 ...

  3. X64下IIS调用32位的dll

    WebAPI项目中遇到了需要调用32位C++的dll的情况,调试的时候能正常调用,但是发布了之后部署在IIS中出现了BadFormatImage异常, 解决方法是在IIS中相应应用程序池=>高级 ...

  4. nodejs 实践:express 最佳实践系列

    nodejs 实践:express 最佳实践系列 nodejs 实践:express 最佳实践(一) 项目结构 nodejs 实践:express 最佳实践(二) 中间件 nodejs 实践:expr ...

  5. JS中关于clientWidth offsetWidth scrollWidth 等的区别

    网页可见区域宽: document.body.clientWidth;网页可见区域高: document.body.clientHeight;网页可见区域宽: document.body.offset ...

  6. ArcMap中提取影像数据边界

    1.前言 客户手里有一些经过裁剪的不规则多边形影像数据(如图例所示),希望能批量获取该类影像的边界信息,即影像对应的面信息,边界线信息.这里我们提供一种利用镶嵌数据集Footprint图层的方法来获取 ...

  7. WORD窗体保护密码清除

    Word 2003破解方法如下:1.用Word打开已设置有密码的“保护文档”(原始DOC文件):2.菜单中选择“文件”→“另存为Web页”,保存为HTML文件然后关闭Word:3.用文本编辑器(如:记 ...

  8. iOS解析新浪微博的@##以及URL链接并展示

    最近在做一个跟微博相关的应用.其中涉及到了对微博中@.##以及URL链接的解析与展示.分享一下个人处理的方式,希望对需要的人有所帮助. 最终的展现效果: 首先,第一步是你得从纯文本中找到它们.毫无疑问 ...

  9. postman传递参数的问题

    postman是一款通过post或者get发送请求测试代码的工具 如果是类的话,就选择JSON格式,如果是一个字段的方法,就直接写入方法值就好了比如 public PageResult<Info ...

  10. 【BZOJ2049】[SDOI2008] Cave 洞穴勘测(LCT维护连通性)

    点此看题面 大致题意: 有\(n\)个洞穴,\(3\)种操作:连一条边,删一条边,询问两点是否联通. \(LCT\)维护连通性 这道题应该是\(LCT\)动态维护连通性的一道模板题. 考虑将\(x\) ...