2016-07-19 28 views
0

をURLに追加します。Pythonは次のように私はURLを持っている

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

を次のように私は、このケースでは「私たちを」ノードを挿入する必要があります。

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' 
>>> 

デフォルトのライブラリを使用してこれを達成するには、より洗練された方法がありますか?

編集: URLの「結果」は固定されていません。「結果」や「製品」や「価格」などがあります。しかし、それは常に 'ボード'の直後になります。

+0

'url.replace( 'results /'、 'results/us /')'? –

答えて

0
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:]) 
関連する問題