urllib.parse

架构概述

urllib.parse 是 Python 的 URL 解析和构造库。它提供了一系列函数,用于解析 URL、连接 URL、分割 URL 的各个部分、编码和解码 URL 组件等。这个库在处理网络请求和操作 URL 时非常有用。

基础功能

  1. urlparse() - 用于解析 URL。

    • 示例 :

      python 复制代码
      from urllib.parse import urlparse
      result = urlparse('http://www.example.com/index.html;user?id=5#comment')
      print(result)
      • 输出 :

        复制代码
        ParseResult(scheme='http', netloc='www.example.com', path='/index.html', params='user', query='id=5', fragment='comment')
      • scheme: URL的协议,这里是http

      • netloc: 网络位置,通常是域名,这里是www.example.com

      • path: URL的路径,这里是/index.html

      • params: 参数,这里是user

      • query: 查询字符串,这里是id=5

      • fragment: 锚点,也称为片段标识符,这里是comment

  2. urlunparse() - 用于根据组件构造 URL。

    • 示例 :

      python 复制代码
      from urllib.parse import urlunparse
      components = ('http', 'www.example.com', '/index.html', 'user', 'id=5', 'comment')
      print(urlunparse(components))
      • 输出 :

        复制代码
        http://www.example.com/index.html;user?id=5#comment
  3. urlencode() - 用于将字典转换为 URL 编码的查询字符串。

    • 示例 :

      python 复制代码
      from urllib.parse import urlencode
      params = {'id': '5', 'name': 'John Doe'}
      print(urlencode(params))
      • 输出 :

        复制代码
        id=5&name=John+Doe

进阶功能

  1. parse_qs() - 用于将查询字符串解析为字典。

    • 示例 :

      python 复制代码
      from urllib.parse import parse_qs
      query_string = 'id=5&name=John+Doe'
      print(parse_qs(query_string))
      • 输出 :

        复制代码
        {'id': ['5'], 'name': ['John Doe']}
  2. quote() 和 unquote() - 用于 URL 编码和解码。

    • 示例 :

      python 复制代码
      from urllib.parse import quote, unquote
      encoded = quote('Hello World!')
      print(encoded)
      decoded = unquote(encoded)
      print(decoded)
      • 输出 :

        复制代码
        Hello%20World%21
        Hello World!

高级教程

  • 使用 urllib.parse 处理复杂的 URL,例如包含特殊字符或多种参数的 URL。
  • 结合 requests 库使用 urllib.parse 来构建和发送 HTTP 请求。

官方文档链接

  • urllib.parse 官方文档
    这个教程涵盖了 urllib.parse 的主要功能。如果你有更具体的问题或需要进一步的示例,请随时告诉我!
相关推荐
岁月宁静5 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者5 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy19907 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk5558 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~14 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享14 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者15 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.16 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人17 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__17 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python