Python中的URL解析 - 规范化路径中的双斜杠

she*_*ron 5 python urlparse

我正在开发一个需要在HTML页面中解析URL(主要是HTTP URL)的应用程序 - 我无法控制输入,其中一些是正如预期的那样有点混乱.

我经常遇到的一个问题是,在解析和加入路径部分中包含双斜线的URL时,urlparse是非常严格的(甚至可能是错误的?),例如:

testUrl = 'http://www.example.com//path?foo=bar'
urlparse.urljoin(testUrl, 
                 urlparse.urlparse(testUrl).path)
Run Code Online (Sandbox Code Playgroud)

而不是预期的结果http://www.example.com//path(甚至更好,使用标准化的单斜杠),我最终得到了http://path.

我正在运行这样的代码的原因是因为这是我到目前为止发现的唯一一种从URL中删除查询/片段部分的方法.也许有更好的方法,但我找不到一个.

任何人都可以推荐一种方法来避免这种情况,或者我应该使用(相对简单,我知道)正则表达式来自我规范化路径?

dbr*_*dbr 6

//path仅路径()无效,这会混淆函数并被解释为主机名

http://tools.ietf.org/html/rfc3986.html#section-3.3

如果URI不包含权限组件,则路径不能以两个斜杠字符("//")开头.

我不是特别喜欢这些解决方案,但它们有效:

import re
import urlparse

testurl = 'http://www.example.com//path?foo=bar'

parsed = list(urlparse.urlparse(testurl))
parsed[2] = re.sub("/{2,}", "/", parsed[2]) # replace two or more / with one
cleaned = urlparse.urlunparse(parsed)

print cleaned
# http://www.example.com/path?foo=bar

print urlparse.urljoin(
    testurl, 
    urlparse.urlparse(cleaned).path)

# http://www.example.com//path
Run Code Online (Sandbox Code Playgroud)

根据您的操作,您可以手动加入:

import re
import urlparse

testurl = 'http://www.example.com//path?foo=bar'
parsed = list(urlparse.urlparse(testurl))

newurl = ["" for i in range(6)] # could urlparse another address instead

# Copy first 3 values from
# ['http', 'www.example.com', '//path', '', 'foo=bar', '']
for i in range(3):
    newurl[i] = parsed[i]

# Rest are blank
for i in range(4, 6):
    newurl[i] = ''

print urlparse.urlunparse(newurl)
# http://www.example.com//path
Run Code Online (Sandbox Code Playgroud)


Eri*_*tin 5

如果您只想获取没有查询部分的 url,我将跳过 urlparse 模块,只需执行以下操作:

testUrl.rsplit('?')
Run Code Online (Sandbox Code Playgroud)

url 将位于返回列表的索引 0 处,查询位于索​​引 1 处。

不可能有两个“?” 在一个网址中,所以它应该适用于所有网址。