Проблемы с кодировкой при парсинге на Python
до выполнения get вывел title и выводится в консоли в читабельном формате на русском, а как запускаю сервер то там { "title": "\u0426\u0435\u043d\u0430 \u043e\u0442: 596\u00a0000\u20b8" } не знаю уже что делать, на странице с которой парсил кодировка UTF-8
from flask_restful import Api, Resource
from bs4 import BeautifulSoup
import requests
app = Flask(__name__)
api = Api(app)
url = "https://poedem.kz/hotoffers" # Replace with the actual URL
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
info_div = soup.find("div", class_="hotoffer-item__price")
title = info_div.text.strip()
print("Title:", title.encode("utf-8").decode("utf-8"))
class ExternalInfo(Resource):
def get(self):
# URL of the website you want to scrape
url = "https://poedem.kz/hotoffers" # Replace with the actual URL
# Send a GET request to the website
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the HTML content of the page
soup = BeautifulSoup(response.text, "html.parser")
# Find the div with the specified class
info_div = soup.find("div", class_="hotoffer-item__price")
if info_div:
# Extract information from the div
title = info_div.text.strip()
# Assume other information is in sibling div elements
return {"title": title}, 200
else:
return {
"error": "Div with class 'TVHotResort TVHotTitle' not found"
}, 500
else:
return {
"error": "Failed to retrieve information from the external website"
}, 500
api.add_resource(ExternalInfo, "/travel")
if __name__ == "__main__":
app.run(debug=True)
Ответы (1 шт):
Для решения проблемы с кодировкой при парсинге на Python, можно попробовать использовать метод encode('latin1').decode('utf-8') вместо encode("utf-8").decode("utf-8") для преобразования строки в правильный UTF-8 формат. Также, можно убедиться, что веб-сайт, с которого ты извлекаешь информацию, действительно использует UTF-8 для своего контента.
Пример:
title = info_div.text.strip()
print("Title:", title.encode("latin1").decode("utf-8"))
Также, если тебе нужны обработки кириллических символов в Flask, можно установить кодировку по умолчанию в файле app.py:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')