Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'latin-1' codec can't encode characters

My code works fine for English text, but doesn't work for for Russian search_text. How can I fix it?

Error text

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 41-46: Body ('Москва') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.

My code

import requests

# search_text = "London" # OK: for english text
search_text = "Москва" # ERROR: 'latin-1' codec can't encode characters in position 41-46: Body ('Москва')
headers = {
    'cookie': 'bci=6040686626671285074; _statid=a741e249-8adb-4c9a-8344-6e7e8360700a; viewport=762; _hd=h; tmr_lvid=ea50ffe34e269b16d061756e9a17b263; tmr_lvidTS=1609852383671; AUTHCODE=VCmGBS9d9sIxDnxN-hzApvPxPoLNADWCZLYyW8JOTcolv2dJjwH7ALYd8dNP9ljxZZuLvoKsDXgozEUt-PjSwXYEDt4syizx1I2LS58gb49kCFae-5uIap--mtLsff2ZqGbFqK5r7buboZ0_3; JSESSIONID=adca48748b8f0c58a926f5e4948f42c0c0aa9463798a9240.1f3566ed; LASTSRV=ok.ru; msg_conf=2468555756792551; TZ=6; _flashVersion=0; CDN=; nbp=; tmr_detect=0%7C1609852395541; cudr=0; klos=0; tmr_reqNum=4; TZD=6.200; TD=200',
}

data = '''{\n "id": 24,\n "parameters": {\n "query": "''' + search_text + '''"\n }\n}'''

response = requests.post('https://ok.ru/web-api/v2/search/suggestCities', headers=headers, data=data)

json_data = response.json()
print(json_data['result'][0]['id'])

I tried

city_name = city_name.encode('utf-8')

but received TypeError: must be str, not bytes

like image 411
swor Avatar asked Dec 18 '25 08:12

swor


1 Answers

Try adding this after the line where you create the data variable before you post the request

data=data.encode() #will produce bytes object encoded with utf-8
like image 175
Matt Miguel Avatar answered Dec 19 '25 23:12

Matt Miguel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!