Часть с пасингом полностью совпадает с другими парсерами, опубликованными в данном разделе ранее. Там же можно посмотреть описание работы, код парсера с комментариями. Отличается только последняя часть с публикацией — после сбора данных текст публикуется в указанной группе телеграм.
Общая схема аналогична. Из файла берется список категорий на Litres, во втором файле хранится список уже опубликованных книг. Если дубль — пропускается.
Используется API телеграмм. К записи прикрепляется картинка.

Код с комментариями ниже.
import requests
from time import sleep
import os
import random
import re
cookies = {} # нужно указать свои данные
headers = {}
all_count = 0
options = '?art_types=text_book&art_types=audiobook&languages=ru'
ref = '?lfrom=477110899'
with open("new.txt", "r", encoding="utf-8") as file_cl:
category_list = file_cl.read().split('\n')
with open("id.txt", "r", encoding="utf-8") as file_id:
all_id = file_id.read().split('\n')
file_id.close()
TOKEN = "6344636955:AAHdb-i-jMOJ**********" # доступ к чату
chat_id = "12345678"
random.shuffle(category_list) # обход категорий, сбор ссылок в список
count_cat = len(category_list) + 1
for category in category_list:
count_cat -= 1
sleep(20)
req = requests.get(f'{category}{options}', headers=headers, cookies = cookies)
src = req.text
with open(f"temp_html/current_category.html", "w", encoding="utf-8") as file:
file.write(src)
with open(f"temp_html/current_category.html", encoding="utf-8") as file:
src = file.read()
soup = BeautifulSoup(src, "lxml")
try:
name_category = soup.find("div", class_="Genre-module__title__name_JuQ14").text
except:
print('ошибка, пропуск')
continue
name_category_clear = name_category.replace('/', '')
if not os.path.exists(f'temp_html/{name_category_clear}/'):
os.makedirs(f'temp_html/{name_category_clear}/')
list_href = soup.find_all('a', {'data-testid': ['art__title']})
for href in list_href: # обход списка ссылок текущей категории
title, author, isbn, description, id, count_author = '', '', '', '', '', ''
link = (f"{href.get('href')}")
id = ((link.split('-'))[-1])[:-1]
if id in all_id:
print(f'дубль - {id} -- осталось категорий: {count_cat}-- добавлено: {all_count}')
continue
sleep(30)
all_id.append(id)
all_count += 1
print(f'новый - {id} -- {all_count} -- осталось категорий: {count_cat}')
with open("id.txt", "a", encoding="utf-8") as file_id:
file_id.write(f'{id}\n')
req = requests.get(f"https://www.litres.ru{link}", headers=headers, cookies = cookies)
src = req.text
with open(f"temp_html/{name_category_clear}/{id}.html", "w", encoding="utf-8") as file_book:
file_book.write(src)
with open(f"temp_html/{name_category_clear}/{id}.html", "r", encoding="utf-8") as file_book:
src = file_book.read()
soup = BeautifulSoup(src, "lxml")
title = soup.find("h1").text
if soup.find(class_="Authors-module__authors_2_blq"):
count_author = soup.find(class_="Authors-module__authors_2_blq").find("h4").text
isbn = soup.find("span", itemprop="isbn") # не используется, но при необходимости можно добавить
if isbn:
isbn = isbn.text
if soup.find(class_="Authors-module__authors_2_blq"):
author = soup.find("div", class_="Authors-module__authors__wrapper_1rZey").find_all("span", itemprop="name")
for i in range(len(author)):
if author[i]:
author[i] = author[i].text
author = ', '.join(map(str, author))
try:
description = soup.find(class_="BookCard-module__book__annotation_2ZIhf").find_all('p')
except:
print('ошибка, пропуск')
continue
attachment_url = f'image/{id}.jpg' # ссылка на картинку. Далее формируем нужный текст и публикуем.
ch_n = '\n'
message = f'{title}{ch_n}{author}{ch_n}{ch_n}{("".join(map(str, description))).split("</p>")[0]}{ch_n}{ch_n}https://www.litres.ru{link}{ref}'
message = message.replace("</p>", "\n")
message = re.sub('<[^<]+?>', '', message)
url = f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&text={message}&photo={attachment_url}"
resw = (requests.get(url).json()) # Эта строка отсылает сообщение