簡體   English   中英

python 請求模塊請求參數編碼 url 與預期的 url 不同

[英]python requests module request params encoded url is different with the intended url

我在 python 項目請求模塊上的 url 編碼有問題。

這些是我從wireshark數據包中獲得的兩個不同的url編碼參數

  1. 0900+%28%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD+%ED%91%9C%EC%A4%80%EC%8B%9C%29
  2. 0900%20(%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD%20%ED%91%9C%EC%A4%80%EC%8B%9C)

'1' 是 python 請求模塊編碼 url 和 '2' 是 url 來自 Z2567Z940EC970E061893 的 C 瀏覽器發送的數據包。 當我解碼它們時,它顯示相同的 utf-8 文本。

似乎它們之間對空格和括號的處理是不同的。 有沒有辦法可以將“1”更改為“2”?

這是我用來發送請求的代碼

_url = "http://something"
_headers = {
    'Accept': 'text/javascript',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'ko-KR',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}
_params = {
    'action': 'log',
    'datetime': '0900 (대한민국 표준시)'
    }

# This is the request part
session = requests.Session()
res = session.get(_url, headers=_headers, params=_params)

您可以手動編碼您的_params以構造您的查詢字符串,然后將其連接到您的_url

您可以使用urllib.parse.urlencode [Python-Docs]將您的_params字典轉換為百分比編碼的 ASCII 文本字符串。 生成的字符串是一系列由&字符分隔的key=value對,其中 key 和 value 都使用quote_via function 引用。 默認情況下, quote_plus()用於引用值,這意味着空格被引用為+字符和/字符被編碼為%2F ,這遵循 GET 請求的標准 (application/x-www-form-urlencoded)。 可以作為 quote_via 傳遞的替代quote_viaquote() ,它將空格編碼為%20而不是編碼/字符。 為了最大限度地控制引用的內容,請使用quote並指定安全值。


from urllib.parse import quote_plus, quote, urlencode
import requests

url_template = "http://something/?{}"
_headers = { ... }
_params = {"action": "log", "datetime": "0900 (대한민국 표준시)"}
_url = url_template.format(urlencode(_params, safe="()", quote_via=quote))

response = requests.get(_url, headers=_headers)

暫無
暫無

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

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