簡體   English   中英

Python 請求編碼問題

[英]Python requests encoding issues

我使用 python 請求向此url發出獲取請求。 這是代碼片段。

url = 'http://213.139.159.46/prj-wwvauskunft/projects/gus/daten/index.jsp?'
params = {'id': 2619521210}

response = requests.get(
    url,
    params=params
)

print(response.status_code)

text = response.text
content = response.content

我在 Python2.7 和 Python3.6 中運行相同的代碼

當我比較兩個版本之間的文本變量時,它們是不同的。 但是兩個版本之間的內容是一樣的。 我很困惑為什么內容相同但文本不同。 如果他們使用相同的編碼將文本編碼為內容,那么文本不應該相同嗎?

我使用chardet來檢測內容的編碼,兩個版本都以ISO-8859-1結尾。 他們不使用utf-8的可能原因是什么。 這只是一種偏好嗎?

另外,當我這樣做時:

content.replace('span', '')

在 Python2 中,它可以工作。 在 Python3 中,它會拋出這個錯誤。 TypeError: a bytes-like object is required, not 'str' (使用b'span'b''可以解決問題)

但是當我這樣做時:

text.replace('span', '')

兩個版本都有效。 這是為什么?

不保證Python 2Python 3兼容性(既不向后也不向前)。 閱讀例如Python 2 與 Python 3:主要差異 例如,如果您的腳本已修改(在末尾添加以下代碼段):

print('type(text)   ', type(text))
print('type(content)', type(content))

Output

py -2 D:\Python\SO3\61954902.py
 200 ('type(text) ', <type 'unicode'>) ('type(content)', <type 'str'>)
py -3 D:\Python\SO3\61954902.py
 200 type(text) <class 'str'> type(content) <class 'bytes'>

為了完整起見,腳本如下:

type D:\Python\SO3\61954902.py
 import requests url = 'http://213.139.159.46/prj-wwvauskunft/projects/gus/daten/index.jsp?' params = {'id': 2619521210} response = requests.get( url, params=params ) print(response.status_code) text = response.text content = response.content print('type(text) ', type(text)) print('type(content)', type(content))

暫無
暫無

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

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