跳转到主要内容

使用urllib处理URL有点痛苦。urlkit让这一切变得容易多了。

项目描述

urlkit

在Python中使用URL很糟糕。直到现在。

以前,处理URL的方法是使用urllib。这总是难以记住,而且非常冗长。例如,让我们以一个URL为例,更改其中一个查询参数

from urllib.parse import urlparse, parse_qs, urlencode, urlunparse

url_string = "http://example.com/?foo=bar&baz=qux"
# Parse the URL into components
parsed_url = urlparse(url_string)

# Parse the query string into a dictionary
query_params = parse_qs(parsed_url.query)

# Modify the specified query parameter
query_params[param] = [new_value]

# Reconstruct the query string
new_query = urlencode(query_params, doseq=True)

# Rebuild the URL with the updated query string
new_url = urlunparse((
    parsed_url.scheme,     # Scheme (e.g., http)
    parsed_url.netloc,     # Network location (e.g., example.com)
    parsed_url.path,       # Path (e.g., /)
    parsed_url.params,     # Parameters (if any)
    new_query,             # New query string
    parsed_url.fragment    # Fragment (if any)
))

现在有了urlkit

from urlkit.http_url import HttpUrl

url_string = "http://example.com/?foo=bar&baz=qux"
# Parse the URL
url = HttpUrl.parse(url_string)

# Set the parameter
url.query["foo"] = "Hello"

# Generate the new URL
new_url = str(url)

urlkit的目标是使一切更加简单和容易。

URL类型支持

表中的类型旨在具有最终功能。它显示目前支持哪些类型。

类型 支持 备注
HTTP 尽可能多地遵循RFC 1738提供完整的支持。
HTTPS 尽可能多地遵循RFC 1738提供完整的支持。
FTP
文件
Mailto
Telnet

示例用法

构建URL

url = HttpUrl(scheme="http", host="example.com", port=12345, query={"search_text": "Hello World"})
str(url) # http://example.com:12345/?search_text=Hello%20World

url = HttpUrl(scheme="http", host="example.com", query={"search_text": "Hello World"}, query_options=QueryOptions(space_encoding=SpaceEncoding.PLUS))
str(url) # http://example.com:12345/?search_text=Hello+World

url = HttpUrl(scheme="http", host="example.com", query="some%20pre-encoded%20text")
str(url) # http://example.com/?some%20pre-encoded%20text

解析URL

# Parsing a HTTP(s) URL:
http_url = HttpUrl.parse("http://username:password@example.com/search?description=Some%20Text")
http_url.path # /search
http_url.query # {"description": "Some Text"}
http_url.password # password

修改URL

url = HttpUrl.parse("http://example.com/foo/bar") # http://example.com/foo/bar
url.path.append("baz") # http://example.com/foo/bar/baz
url.path.append("one/two") # http://example.com/foo/bar/baz/one/two
url.path.pop_last() # http://example.com/foo/bar/baz/one
url.path.pop_last() # http://example.com/foo/bar/baz
url.path.pop_last() # http://example.com/foo/bar
url.path.append(["baz", "one", "two"]) # http://example.com/foo/bar/baz/one/two

明确不支持的功能

具有相同键的多个查询参数

URL已经过时。它们有很多冗余,这可能使它们难以处理。例如,许多实现(如urllib)允许查询参数出现多次。所以如果你使用URL http://example.com/?param=1&param=2 并尝试获取param的结果,你会得到一个列表:["1", "2"]。这可能很好。然而,缺点是每次查询参数时,即使它们几乎总是只出现一次,你都会得到一个列表。即 https://example.com/?param=1 返回 ["1"]

项目详细信息


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分发

urlkit-0.2.2.tar.gz (10.8 kB 查看哈希值)

上传时间: 源代码

构建分发

urlkit-0.2.2-py3-none-any.whl (11.2 kB 查看哈希值)

上传时间: Python 3

支持者