如何将URL分为三个不同的变量

Aru*_*ath 3 python split python-3.x

我想将一个URL分成三个字符串。例:

https://www.google.com:443
http://amazon.com:467
Run Code Online (Sandbox Code Playgroud)

我希望输出为:

string 1: https or http
string 2: www.google.com or amazon.com
string 3: 443 or 467
Run Code Online (Sandbox Code Playgroud)

以上输出基于提供的示例。基本上我想分割字符串成protocoldomainport和分配给三个不同的变量。

Mar*_*yer 6

ULR比人们想象的要复杂,这就是为什么使用经过验证的代码来解析它们并处理意外边缘情况通常是一个好主意的原因。Python urllib.parse在该库中,您应该使用该库,而不是尝试自行解析。

你想要的部分都在schemehostnameport对象的属性从返回urlsparse()

例如:

from urllib.parse import urlparse

def getParts(url_string):
    p = urlparse(url_string)
    return [p.scheme, p.hostname, p.port]

getParts('https://www.google.com:443')
# ['https', 'www.google.com', 443]

getParts('http://amazon.com:467')
# ['http', 'amazon.com', 467]

# surprising, but valid url:
getParts('https://en.wikipedia.org:443/wiki/Template:Welcome')
# ['https', 'en.wikipedia.org', 443]

# missing parts:
getParts('//www.google.com/example/home')
# ['', 'www.google.com', None]
Run Code Online (Sandbox Code Playgroud)