簡體   English   中英

將Python .format()添加到url但拋出KeyError

[英]Python .format() added to an url but throws a KeyError

我想將一個帶有.format()的變量添加到URL,但是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 = '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

如果要打印文字大括號並使用格式,則必須將其加倍。

因此它應該是params={{"page":{}}}而不是params={"page":{}} callback_params相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM