iT邦幫忙

0

python從websocket接收資料,出現'cp950'編碼錯誤

2024-04-30 17:28:57519 瀏覽
  • 分享至 

  • xImage

我從websocket要接資料,但一直跳出
'cp950' codec can't encode character '\u0410' in position 0: illegal multibyte sequence
這樣的錯誤訊息,有詢問server端他們也是使用utf-8編碼也都英文
但還是不斷跳出error
導致我都看不到他們發的資料

他們只有建議我使用java來接資料
不知道各位有沒有遇到過這樣的問題

感謝各位的解答~

async def connect_websocket():
    url = "wss://api"
    async with websockets.connect(url) as websocket:
        print("WebSocket connected.")
        await authorize(websocket)  # 發送授權
        # 等待回應
        response = await websocket.recv()
        print(f'Received response: {response}')
        if 'authorized' in str(response):
            await subscribe(websocket)  # 發送訂閱消息
        async for message in websocket:
        # 解碼JSON訊息
            try:
                # 解码JSON消息
                data = json.loads(message)
                if data['cmd']=='outcomes':
                ###outcome的資料都可沒問題
                    for odds in data['msg']:
                        ###只看要的玩法
                        if odds[4] not in [1,5,7]:continue
                        # print(odds)
                else:
                ###另一種資料大多都會跳出'cp950'錯誤
                    print(data)
            except Exception as e:
                print(e)
asyncio.run(connect_websocket())

錯誤訊息如下: 就是特定幾個都無法解讀
https://ithelp.ithome.com.tw/upload/images/20240430/20132078fsGqkGUsUJ.jpg

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2024-04-30 17:46:39 檢舉
這訊息表示你是用cp950(大五碼)在解碼的,系統是Linux的話看一下主機的locale
看一下程式文件的編碼。
是不是什麼DOS、ANSI啥的。
那也會影響到。
網路傳輸都是 byte array 格式,接收之後要轉成字串,必須指定正確的內碼,目前出現的錯誤是傳送的內容可能是UTF-8,但程式轉換未指定內碼,因此,就出現cp950 error. 注意,cp950是python 預設的內碼 for 台灣。
iT邦新手 5 級 ‧ 2024-05-02 10:29:08 檢舉
感謝各位大大解答
後來使用message.encode("utf8").decode("cp950", "ignore")
就可以順利看到資料
((後來才發現資料是俄文 不知是不是因為這樣才那麼麻煩
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答