Mak*_*nko 43
您可以使用urlparse从URL字符串中获取主机名:
from urlparse import urlparse
print urlparse("http://www.website.com/abc/xyz.html").hostname # prints www.website.com
Run Code Online (Sandbox Code Playgroud)
dfo*_*tic 11
>>> from urlparse import urlparse
>>> aaa = urlparse('http://www.acme.com:456')
>>> aaa.hostname
'www.acme.com'
>>> aaa.port
456
>>>
Run Code Online (Sandbox Code Playgroud)
它失败的原因是:
www.acme.com 456
Run Code Online (Sandbox Code Playgroud)
是因为它不是有效的URI.你为什么不这样做:
: urlparse方法解析生成的字符串尽可能多地尝试使用默认功能,特别是在解析像URI这样的知名格式时.
我对urlparse不太熟悉,但是使用正则表达式可以执行以下操作:
p = '(?:http.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*'
m = re.search(p,'http://www.abc.com:123/test')
m.group('host') # 'www.abc.com'
m.group('port') # '123'
Run Code Online (Sandbox Code Playgroud)
或者,没有端口:
m = re.search(p,'http://www.abc.com/test')
m.group('host') # 'www.abc.com'
m.group('port') # '' i.e. you'll have to treat this as '80'
Run Code Online (Sandbox Code Playgroud)
编辑:固定正则表达式也匹配“ www.abc.com 123”