[英]Python Socket utf-8 decoding
我想將 GET 請求的響應轉換為字符串,我想出了以下代碼:
import socket target_host = "www.google.com" target_port = 80 # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect the client s.connect((target_host, target_port)) # send some data request = "GET / HTTP/1.1\\r\\nHost:%s\\r\\n\\r\\n" % target_host s.send(request.encode("utf-8")) full_msg = "" # Prevent recv() function to stop the script to wait until it receives more data, even if there is no more. s.settimeout(1) flag = True while flag: # receive some data try: response = s.recv(4096) full_msg = full_msg + str(response) print("Adding msg") except Exception as e: print(full_msg) flag = False print(e) print("Loop ended") print(type(full_msg))
response = s.recv(4096).decode("utf-8")
我收到以下異常:
'utf-8' codec can't decode byte 0xe8 in position 1025: invalid continuation byte
我不知道如何解決這個問題,因為我無法修改我從響應中得到的字符,我需要刪除“b'”字符,如果我每次都沒有解碼它會弄亂我的 full_msg 字符串環形。
此外,在文檔中它說 .recv() 方法返回一個字符串,但我似乎得到了一個類似字節的對象。 歡迎任何想法,我也很樂意知道我的代碼可以改進的任何方式。根據您響應中的數據, Content-Type: text/html; charset=ISO-8859-1
Content-Type: text/html; charset=ISO-8859-1
。 響應不是 UTF-8。 .decode('iso-8859-1')
代替。 更好的是使用requests :
import requests
r = requests.get('https://www.google.com')
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
# print(r.text) # already decoded with r.encoding
# print(r.content) # byte string of original encoded data
# print(r.json()) # If the response is JSON data, This loads the data.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.