我在数据库中有两种类型的地址:
url_1 = "http://country.city.street/"
url_2 = "http://country.city.street:8180/"
我需要获得统一的地址格式 (
url_pattern = "country.city.street"
) 以在 DNS 服务器中使用。我从开头删除了 http://
部分,但在地址末尾无法得到好的结果。有谁知道我可以用什么来获得 url_pattern
标准?
url_1 = "http://country.city.street/"
url_2 = "http://country.city.street:8180/"
url_1 = url_1[7:]
url_2 = url_2[7:]
有标准的URL解析模块
from urllib.parse import urlparse
print(urlparse("http://country.city.street:8180/").hostname)
您可以使用
urllib.parse
模块。它有一个 urlparse
函数,您可以使用它来将 URL 解析为组件。
>>> import urllib.parse
>>> urllib.parse.urlparse("http://country.city.street/")
ParseResult(scheme='http', netloc='country.city.street', path='/', params='', query='', fragment='')
只需检查 liburlparser,我知道这是用 C++ 编写的最快的解决方案。
pip install liburlparser
然后这样做:
from liburlparser import Url
print(Url.extract_host("http://country.city.street:8180/"))
此解决方案是用 C++(而不是 Python)解析字符串时最快的解决方案。但还有一些替代解决方案:
from liburlparser import Host
print(Host.from_url("http://country.city.street:8180/"))
或:
from liburlparser import Url
print(Url("http://country.city.street:8180/").host)
它们的速度对这些解决方案进行排序。