Python urlparser 给出了错误的结果

Python urlparser Gives wrong result

我正在尝试将 url 的不同部分与 python 分开 s url解析,但我似乎在结果中得到了错误的值。

baseline = runSql(conn,"Select url from malware_traffic where tag = 'baseline';")

for i in baseline:
    print i[0]
    print urlparse.urlparse(i[0])

runSql 函数只是 returns 个 url 的列表。我遍历它们并尝试将 urls 从基线变量转换为 urls,但是 python 解析 urls 的方式似乎不正确

172.217.9.174:443/c2dm/register3
ParseResult(scheme='172.217.9.174', netloc='', path='443/c2dm/register3', params='', query='', fragment='')
connectivitycheck.gstatic.com:80/generate_204
ParseResult(scheme='connectivitycheck.gstatic.com', netloc='', path='80/generate_204', params='', query='', fragment='')
www.google.com:80/gen_204
ParseResult(scheme='www.google.com', netloc='', path='80/gen_204', params='', query='', fragment='')
172.217.9.174:443/auth/devicekey
ParseResult(scheme='172.217.9.174', netloc='', path='443/auth/devicekey', params='', query='', fragment='')

在结果中你可以清楚地看到它混淆了 scheme 和 netloc 以及在路径中包含端口。

例如第一个结果应该是这个。

ParseResult(scheme='', netloc='172.217.9.174:443', path='/c2dm/register3', params='', query='', fragment='')

不知道为什么会搞砸。

我实际上使用的是与此处文档中的示例之一相同的东西 https://docs.python.org/2/library/urlparse.html

那么我做错了什么或者是错误?

问题是您的网址没有方案(http:// 部分),因此 python 认为 172.217.9.174: 是方案。以 http:// 为前缀一切正常:

>>> urlparse('172.217.9.174:443/c2dm/register3')
ParseResult(scheme='172.217.9.174', netloc='', path='443/c2dm/register3', params='', query='', fragment='')
>>> urlparse('http://172.217.9.174:443/c2dm/register3')
ParseResult(scheme='http', netloc='172.217.9.174:443', path='/c2dm/register3', params='', query='', fragment='')