【问题标题】:Python add to urlPython添加到网址
【发布时间】:2016-07-19 15:28:41
【问题描述】:

我的网址如下:

http://www.example.com/boards/results/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01

在这种情况下我需要插入一个节点'us',如下:

http://www.example.com/boards/results/us/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01

使用 Python 的 urlparse 库,我可以得到如下路径:

path = urlparse(url).path

...然后使用一个复杂而丑陋的例程,包括根据斜杠分割路径并插入新节点,然后重建 URL

>>> path = urlparse(url).path
>>> path.split('/')
['', 'boards', 'results', 'current:entry1,current:entry2', 'modular', 'table', 'alltables', 'alltables', 'alltables', '2011-01-01']
>>> ps = path.split('/')
>>> ps.insert(4, 'us')
>>> '/'.join(ps)
'/boards/results/current:entry1,current:entry2/us/modular/table/alltables/alltables/alltables/2011-01-01'
>>> 

有没有更优雅/pythonic 的方式来使用默认库来实现这一点?

编辑: URL 中的“结果”不是固定的——它可以是“结果”或“产品”或“价格”等。但是,它总是在“boards”之后。

【问题讨论】:

  • url.replace('results/', 'results/us/')?

标签: python url urlparse


【解决方案1】:
path = "http://www.example.com/boards/results/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01"
replace_start_word = 'results'
replace_word_length = len(replace_start_word)
replace_index = path.find(replace_start_word)
new_url = '%s/us%s' % (path[:replace_index + replace_word_length], path[replace_index + replace_word_length:])

【讨论】:

    猜你喜欢
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多