所以我有如下数据:
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'
答案 0 :(得分:2)
这是一个答案,根据要求,使用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)
答案 1 :(得分:0)
这就是你想要的吗?
item_360 = item.replace("=98","=360")
print item_360
'//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'
我把" ="避免在(如果存在)之前替换数字。
对于更复杂的替换,您可以查看regex
因此,如果您不了解98
,则可以使用正则表达式:
import re
item_360 = re.sub("=\d+", '=360', item)
答案 2 :(得分: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)
希望它有所帮助:)
答案 3 :(得分: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,
))