如何用python格式化url中的字符串?

2024-06-01 01:03:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用1个变量格式化链接(link1),但是当我想用2个变量格式化链接(link2)时,它会抛出一个错误(ValueError:索引94处不支持的格式字符“A”(0x41) 链接2应该是:https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=Topper&origin=https%3A%2F%2Fwww.real.de%2Fproduct%2F324093002%2F

有什么解决办法吗

i = 324093002
b = "Topper"
link_product = 'https://www.real.de/product/%s/'
link_keyword = 'https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=*%s*&origin=https%3A%2F%2Fwww.real.de%2Fproduct%2F*%s*%2F'
link1 = link_product %i
link2 = link_keyword % (i, b)

Tags: httpscom链接linkproductwidgetswidgetreal
3条回答

Char%在字符串格式中有特殊的含义,如%s%i等,并且有%3A{}格式不正确。您必须使用%%通知Python您需要普通字符%-%%3A{}

i = 324093002
b = "Topper"
link_keyword = 'https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=*%s*&origin=https%%3A%%2F%%2Fwww.real.de%%2Fproduct%%2F*%s*%%2F'

link2 = link_keyword % (i, b)
print(link2)

我建议使用f字符串格式(>;Python 3.6)。有关更多信息,请参见here

i = 324093002
b = "Topper"
link_product = f"https://www.real.de/product/{i}/"
link_keyword = f"https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=*{i}*&origin=https%3A%2F%2Fwww.real.de%2Fproduct%2F*{b}*%2F"

您应该使用urllib,以防止将数据与已经URL编码的URL混合:

from urllib.parse import urlencode, urljoin, urlparse

i = 324093002
b = "Topper"
link_product = urljoin('https://www.real.de/product/', str(i))

link_url = 'https://widget.s24.com/applications/1e082c83/widgets/422/products?{}'
link_params = {'searchTerm': i, 'origin': link_product}

link_keyword = link_url.format(urlencode(link_params))
print(link_keyword)

输出:

https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=324093002&origin=https%3A%2F%2Fwww.real.de%2Fproduct%2F324093002

注:
特别是当b变成使用非URL安全字符的术语时,如Top topiPhone7+,使用常规字符串格式会把事情搞砸

相关问题 更多 >