Python式的URL解析

0 投票
2 回答
1261 浏览
提问于 2025-04-15 11:41

关于如何在Python中解析URL,有很多问题。这篇文章讨论的是最好的或者说最符合Python风格的方法。

在我的解析过程中,我需要四个部分:网络位置、URL的第一部分、路径、文件名和查询字符串部分。

http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123

应该解析成:

netloc = 'www.somesite.com'
baseURL = 'base'
path = '/first/second/third/fourth/'
file = 'foo.html?abc=123'

下面的代码可以得到正确的结果,但在Python中有没有更好的方法呢?

url = "http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123"

file=  url.rpartition('/')[2]
netloc = urlparse(url)[1]
pathParts = path.split('/')
baseURL = pathParts[1]

partCount = len(pathParts) - 1

path = "/"
for i in range(2, partCount):
    path += pathParts[i] + "/"


print 'baseURL= ' + baseURL
print 'path= ' + path
print 'file= ' + file
print 'netloc= ' + netloc

2 个回答

2

我建议你可以先用 urlparse 这个工具。另外,你还可以使用 rsplit,以及 splitrsplitmaxsplit 参数,这样可以让事情变得简单一些:

_, netloc, path, _, q, _ = urlparse(url)
_, base, path = path.split('/', 2) # 1st component will always be empty
path, file = path.rsplit('/', 1)
if q: file += '?' + q
6

因为你对想要的部分的要求和urlparse提供的内容不一样,所以这就是它能做到的最好效果了。不过,你可以把这个:

partCount = len(pathParts) - 1

path = "/"
for i in range(2, partCount):
    path += pathParts[i] + "/"

换成这个:

path = '/'.join(pathParts[2:-1])

撰写回答