在Python 2中修改URL组件 [英] Modify URL components in Python 2
问题描述
是否有更干净的方法来修改Python 2中URL的某些部分?
Is there a cleaner way to modify some parts of a URL in Python 2?
例如
http://foo/bar -> http://foo/yah
目前,我正在这样做:
import urlparse
url = 'http://foo/bar'
# Modify path component of URL from 'bar' to 'yah'
# Use nasty convert-to-list hack due to urlparse.ParseResult being immutable
parts = list(urlparse.urlparse(url))
parts[2] = 'yah'
url = urlparse.urlunparse(parts)
有更清洁的解决方案吗?
Is there a cleaner solution?
推荐答案
不幸的是,该文档已过时. urlparse.urlparse()
(和urlparse.urlsplit()
)产生的结果使用
Unfortunately, the documentation is out of date; the results produced by urlparse.urlparse()
(and urlparse.urlsplit()
) use a collections.namedtuple()
-produced class as a base.
不要将此namedtuple转换为列表,而要使用为该任务提供的实用程序方法:
Don't turn this namedtuple into a list, but make use of the utility method provided for just this task:
parts = urlparse.urlparse(url)
parts = parts._replace(path='yah')
url = parts.geturl()
通过 namedtuple._replace()
方法,您可以创建替换了特定元素的新副本. ParseResult.geturl()
方法然后重新加入各部分为您找到一个网址.
The namedtuple._replace()
method lets you create a new copy with specific elements replaced. The ParseResult.geturl()
method then re-joins the parts into a url for you.
演示:
>>> import urlparse
>>> url = 'http://foo/bar'
>>> parts = urlparse.urlparse(url)
>>> parts = parts._replace(path='yah')
>>> parts.geturl()
'http://foo/yah'
mgilson 提交了
mgilson filed a bug report (with patch) to address the documentation issue.
这篇关于在Python 2中修改URL组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!