将Python .format()添加到url但抛出KeyError

时间:2019-06-13 20:29:13

标签: python

我想在URL中添加一个带有.format()的变量,但是python抛出KeyError。

我得到的错误:

KeyError: '"page"'

我已经在网址中添加了.format()和{},请参见下面的网址。在url的末尾添加了.format()。

url with .format() / {"page":{}}'.format(valuetest)
url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&callback_params={"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}&action=changePage&params={"page":{}}'.format(valuetest)

original url:
url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&callback_params={"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}&action=changePage&params={"page":1}'

下面是我想要的一个简单示例:

valuetest = '1'
urltest = 'https://www.testing.com{}'.format(valuetest)
print(urltest)

结果:https://www.testing.com1

如何创建URL,以便可以向URL添加变量?

2 个答案:

答案 0 :(得分:1)

您需要转义不属于替换字段的大括号。

url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&callback_params={{"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}}&action=changePage&params={{"page":{}}}'

https://docs.python.org/3/library/string.html#format-string-syntax

答案 1 :(得分:1)

如果要打印文字大括号并使用格式,则必须将其加倍。

因此它应该是params={{"page":{}}}而不是params={"page":{}}。与callback_params相同。