簡體   English   中英

Python 3 requests.get()。text返回未編碼的字符串

[英]Python 3 requests.get().text returns unencoded string

Python 3 requests.get()。text返回未編碼的字符串。 如果我執行:

import requests
request = requests.get('https://google.com/search?q=Кто является президентом России?').text.lower()
print(request)

我得到這樣的:

Кто является презид

我試圖將google.com更改為google.ru

如果我執行:

import requests
request = requests.get('https://google.ru/search?q=Кто является президентом России?').text.lower()
print(request)

我得到這樣的:

d0%9a%d1%82%d0%be+%d1%8f%d0%b2%d0%bb%d1%8f%d0%b5%d1%82%d1%81%d1%8f+%d0%bf%d1%80%d0%b5%d0%b7%d0%b8%d0%b4%d0%b5%d0%bd%d1%82%d0%be%d0%bc+%d0%a0%d0%be%d1%81%d1%81%d0%b8%d0

我需要獲取一個編碼的普通字符串。

您收到此錯誤是因為請求無法識別響應的正確編碼。 因此,如果您對響應編碼有把握,則可以像下面這樣設置:

response = requests.get(url) response.encoding --> to check the encoding response.encoding = "utf-8" --> or any other encoding.

然后使用.text方法獲取內容。

我用urllib.parse.unquote()方法修復了它:

import requests
from urllib.parse import unquote

request = unquote(requests.get('https://google.ru/search?q=Кто является президентом России?').text.lower())
print(request)

暫無
暫無

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

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