【问题标题】:Modify URL components in Python 2在 Python 2 中修改 URL 组件
【发布时间】:2014-08-03 18:10:47
【问题描述】:

在 Python 2 中是否有更简洁的方法来修改 URL 的某些部分?

例如

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)

有更清洁的解决方案吗?

【问题讨论】:

  • “干净”到底是什么意思?

标签: python url python-2.x urlparse


【解决方案1】:

很遗憾,文档已过时; urlparse.urlparse()(和urlparse.urlsplit())产生的结果使用collections.namedtuple()-produced class作为基础。

不要把这个命名元组变成一个列表,而是利用为这个任务提供的实用方法:

parts = urlparse.urlparse(url)
parts = parts._replace(path='yah')

url = parts.geturl()

namedtuple._replace() method 可让您创建替换特定元素的新副本。 ParseResult.geturl() method 然后将这些部分重新加入到您的 url 中。

演示:

>>> import urlparse
>>> url = 'http://foo/bar'
>>> parts = urlparse.urlparse(url)
>>> parts = parts._replace(path='yah')
>>> parts.geturl()
'http://foo/yah'

mgilson 提交了bug report (with patch) 以解决文档问题。

【讨论】:

  • 我要指出这一点。实用方法由namedtuple 返回的子类提供给urlparse.ParseResult。我认为这应该在 2.7 文档中指出,因为如果不知道这一点,您就无法知道 _replace 实际上 此类公共 API 的一部分...跨度>
  • 更有趣的是在文档中提到BaseResult,它根本没有出现在源代码中......(对不起题外话......已经晚了......无论如何+1 )
  • @mgilson:呵呵,确实,这肯定是使用namedtuple之前的遗留物。
  • 谢谢 - 这是一个更好的解决方案。虽然,正如其他 cmets 所指出的那样,仅根据文档似乎没有办法知道它。
  • @GarethStockwell:是的,看起来像一个文档错误;还没有提交,我稍后再提交。
【解决方案2】:

我想正确的做法是这样。

不建议使用_replace私有方法或变量。

from urlparse import urlparse, urlunparse

res = urlparse('http://www.goog.com:80/this/is/path/;param=paramval?q=val&foo=bar#hash')
l_res = list(res)
# this willhave ['http', 'www.goog.com:80', '/this/is/path/', 'param=paramval', 'q=val&foo=bar', 'hash']
l_res[2] = '/new/path'
urlunparse(l_res)
# outputs 'http://www.goog.com:80/new/path;param=paramval?q=val&foo=bar#hash'

【讨论】:

  • 它是公共接口的一部分,它只是以下划线为前缀,以免与实际成员发生冲突。
猜你喜欢
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 2016-05-13
  • 2019-05-08
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多