如何不让调用将 %20 转换为单词之间的 space

How not to let the call convert %20 to a space between words

要向 Telegram 发送消息,我使用此模板:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

urlphoto = f'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'
botalert = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
chatalert = 'yyyyyyyyyyyyyyyy'
urlalert = f"https://api.telegram.org/bot" + botalert + "/sendMessage?text=" + urlphoto + "&chat_id=" + chatalert + "&parse_mode=HTML"
requests.get(urlalert, headers=headers)

但是在发送消息时,那里收到的link并没有在一起,因为%20被转换成了空格:

我应该如何进行才能使 link 像这样完美交付:

http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html

试试这个:

import requests
from requests.utils import quote

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

urlphoto = 'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'
botalert = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
chatalert = 'yyyyyyyyyyyyyyyy'
urlalert = f"https://api.telegram.org/bot{botalert}/sendMessage"
requests.get(urlalert, params=quote(f"?text={urlphoto}&chat_id={chatalert}&parse_mode=HTML"), headers=headers)

您可以这样定义 urlphoto:

urlphoto = f'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'.replace('%20', '%2520')

这将打印百分号后跟 20。

使用参数字典,将为您正确编码参数:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

urlphoto = f'http://127.0.0.1:0001/Home/Site%20de%20Trabalho%20-%20Home.html'
botalert = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
chatalert = 'yyyyyyyyyyyyyyyy'
urlalert = f'https://api.telegram.org/bot{botalert}/sendMessage'
params = {'text':urlphoto, 'chat_id':chatalert, 'parse_mode':'HTML'}
requests.get(urlalert, headers=headers, params=params)