擅长:python、mysql、java
<p>我对urlparse不太熟悉,但使用regex,您可以执行以下操作:</p>
<pre><code>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'
</code></pre>
<p>或者,没有端口:</p>
<pre><code>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'
</code></pre>
<p>编辑:修复了regex,使其也与“www.abc.com 123”匹配</p>