Некорректная кодировка данных в таблице
Решил написать парсер. В процессе написания решил, что надо данные записывать в таблицу, но, увидев результат, сразу расстроился: как я понимаю, проблема с кодировкой, но не очень понимаю, как ее решить:
import requests
from bs4 import BeautifulSoup
import csv
CSV = 'cards.csv'
HOST = 'https://ural-toys.ru/'
URL = 'https://ural-toys.ru/catalog/all/'
HEADERS = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
}
def get_html(x):
r = requests.get('https://ural-toys.ru/catalog/all/' + str(x) + str('-50/1-0/0-0-0-0-0-0-0-0-0-0-0/'))
return r
def get_content(html):
soup = BeautifulSoup(html,'html.parser')
items = soup.find_all('div', class_ = 'b-catalog__item')
cards = []
for item in items:
cards.append(
{
'title' : item.find('div', class_='b-catalog__item-title-wrap').get_text(strip = True).encode(encoding='utf-8', errors='ignore').decode('utf-8', 'ignore'),
'link_product': HOST + item.find('div', class_='b-catalog__item-title-wrap').find('a').get('href'),
'img': HOST + item.find('div', class_='b-catalog__item-wrap').find('a').get('href'),
'price' : item.find('div', class_='b-catalog__item-price').get_text(strip = True)
}
)
return cards
def save_doc(items, path):
with open(path, 'w', newline='', encoding="utf-8") as file:
writer = csv.writer(file, delimiter = ';')
writer.writerow(['Название продукта', 'Ссылка на продукт', 'Картинка', 'Цена'])
for item in items:
writer.writerow([item['title'],item['link_product'],item['img'],item['price']])
def parser():
PAGENATION = input('Укажите количество страниц для парсинга: ')
PAGENATION = int(PAGENATION.strip())
html = get_html(1)
if html.status_code == 200:
cards = []
stringTwo = '-100'
for page in range(1, PAGENATION):
print(f'Парсинг еще в процессе, страница: {page}')
html = get_html(page)
#pages.append(requests.get('https://ural-toys.ru/catalog/all/' + str(x) + str('-50/1-0/0-0-0-0-0-0-0-0-0-0-0/')))
cards.extend(get_content(html.text))
save_doc(cards, CSV)
print(cards)
else:
print('Error')
parser()
# max_page = 2
# pages = []
#
# for x in range(1, max_page + 1):
# pages.append( requests.get('https://ural-toys.ru/catalog/all/' + str(x) + str('-50/1-0/0-0-0-0-0-0-0-0-0-0-0/' ) ) )
#
# for r in pages:
# html = BeautifulSoup(r.content, 'html.parser')
#
# for el in html.select('.b-catalog__item'):
# title = el.select('.b-price__num')
# print( title[0].text
Ответы (1 шт):
Автор решения: Александр Плетнев
→ Ссылка
Решение нашел:
with open(path, 'w+', newline='', encoding="cp1251", errors='replace') as file:
