2

所以我有一个数据如下:

 item = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'

使用 urlparse 模块。如何用新大小替换上述数据,使其看起来像这样:

  item = '//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'
4

4 回答 4

7

Here is an answer which, as requested, uses urlparse:

import urllib
import urlparse

url = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'
parts = urlparse.urlparse(url)
query_dict = urlparse.parse_qs(parts.query)  # {'wid': ['98'], 'hei': ['98']}
query_dict['wid'] = '360'
query_dict['hei'] = '360'
new_parts = list(parts)
new_parts[4] = urllib.urlencode(query_dict)
print urlparse.urlunparse(new_parts)
于 2014-10-06T18:12:28.843 回答
0

那是你要的吗 ?

item_360 = item.replace("=98","=360")
print item_360
'//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'

我放了“=”以避免在之前替换数字(如果存在)。

对于更复杂的替换,您可以查看正则表达式

所以,如果你不知道98,你可以使用正则表达式:

import re
item_360 = re.sub("=\d+", '=360', item)
于 2014-10-06T17:54:39.063 回答
0

如果 hei 和 wid 总是等于一个数,那么我们有:

 a = item[item.find('=')+1:item.find('&')] #this is the number in url (in your example it is 98
 item.replace(a, '360')   #item.replace(a, NewNumber) 

希望能帮助到你 :)

于 2014-10-06T17:55:48.543 回答
0

我喜欢这样做以使其易于阅读:

from urllib.parse import urlsplit, urlunsplit, urlencode

split = urlsplit(url)
new_url = urlunsplit((
    split.scheme,
    split.netloc,
    split.path,
    urlencode(dict(hei=360, wid=360)),
    None,
))
于 2021-06-23T00:13:55.883 回答