what's wrong with that code:
def get_books_sel(pages_count=1):
# Удаляем старую папку с обложками и создаем новую
if os.path.exists(BOOKS_COVERS_PATH):
shutil.rmtree(BOOKS_COVERS_PATH)
os.mkdir(BOOKS_COVERS_PATH)
code
Assistant
# Загружаем авторов из CSV файла
authors_df = pd.read_csv("authors.csv", delimiter=";")
authors = authors_df.to_dict('records')
books_counter = 0
# Настройка Selenium
options = Options()
options.add_argument('--headless') # Запуск в фоновом режиме
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
for author in authors:
books = []
genres = []
books_genres = []
# Формируем URL для книг
books_url = urljoin(LIVELIB_BASE_URL, f"/author/{author['Link'].split('/')[-1].split('-')[0]}/top/work/listview/biglist/~")
for i in range(1, pages_count + 1):
driver.get(books_url + str(i))
time.sleep(2) # Даем время для загрузки страницы
names = driver.find_elements(By.CSS_SELECTOR, "ul#author-objects li")
for index, name in enumerate(names):
title = name.find_element(By.CSS_SELECTOR, "a.book-item__title").text
print(title)
# Получаем детальную информацию о книге
book_detail_url = urljoin(LIVELIB_BASE_URL, name.find_element(By.CSS_SELECTOR, "a.book-item__title").get_attribute("href"))
driver.get(book_detail_url)
print(book_detail_url)
time.sleep(2)
annotation = driver.find_element(By.CSS_SELECTOR, "summary.bc-card__text-block-txt.ugc-content").text
#print(annotation)
# Получаем жанры
genres_tags = driver.find_elements(By.CSS_SELECTOR, "a.bc-info__link.bc-info__link_type_category")
for i, genre in enumerate(genres_tags):
genre_title = genre.text.replace("№2 в ", "").strip()
genre_id = next((gen["Id"] for gen in genres if gen['Title'] == genre_title), None)
if genre_id is None:
genres.append({"Id": len(genres), "Title": genre_title})
genre_id = len(genres) - 1
books_genres.append({"Book_id": books_counter, "Genre_id": genre_id})
# Получение изображения
labi_url = f"https://www.labirint.ru/search/{author['Author'].replace(' ', '%20')}%20{title.replace(' ', '%20')}/?stype=0"
driver.get(labi_url)
time.sleep(2)
image = driver.find_element(By.CSS_SELECTOR, "div.product-card img")
img_ratio = fuzz.WRatio(image.get_attribute("title"), f"{author['Author']} {title}")
print(img_ratio)
if img_ratio > 80:
img_path = os.path.join(BOOKS_COVERS_PATH, os.path.basename(image.get_attribute("data-src")) + ".webp")
with open(img_path, "wb") as f:
f.write(requests.get(image.get_attribute("data-src")).content)
else:
img_path = os.path.join(BOOKS_COVERS_PATH, f"{books_counter}_{os.path.basename(name.find_element(By.CSS_SELECTOR, 'img').get_attribute('data-pagespeed-lazy-src'))}")
with open(img_path, "wb") as f:
f.write(requests.get(name.find_element(By.CSS_SELECTOR, "img").get_attribute('data-pagespeed-lazy-src')).content)
books.append({
"Id": books_counter,
"Title": title,
"Avatar": img_path,
})
books_counter += 1
df = pd.DataFrame(books)
df.to_csv("books.csv", sep=';', encoding='utf-8', index=False)
df.to_excel("books.xlsx")
df = pd.DataFrame(genres)
df.to_csv("genres.csv", sep=';', encoding='utf-8', index=False)
df.to_excel("genres.xlsx")
driver.quit()
df = pd.DataFrame(books_genres)
df.to_csv("books_genres.csv", sep=';', encoding='utf-8', index=False)
df.to_excel("books_genres.xlsx")
print(books)
print(genres)
print(books_genres)
exit()
The code you provided appears to have several issues and areas for improvement. Here are some of the key issues and suggestions for improvements:
Imports Missing: You didn't include necessary imports such as import os, import shutil, import time, from urllib.parse import urljoin, from selenium import webdriver, from selenium.webdriver.chrome.service import Service, from selenium.webdriver.chrome.options import Options, from webdriver_manager.chrome import ChromeDriverManager, import pandas as pd, and from fuzzywuzzy import fuzz. Ensure you import all the necessary modules.
Global Constants: Variables like BOOKS_COVERS_PATH and LIVELIB_BASE_URL are used without being defined. Make sure these constants are defined before they are used.
Incorrect Placement of driver.quit(): driver.quit() is placed inside the loop over authors, meaning the driver will quit after processing the first author, which will cause an error when trying to access the driver again in the next iteration. Move driver.quit() outside of the loop.
Exit Statement: You are using exit() inside the loop. This will terminate the execution after processing the first author. This statement should be removed or placed outside the loop if necessary.
CSV and Excel Writing: You are repeatedly overwriting the CSV and Excel files for each author because you write them inside the loop. Consider writing these files after the loop, aggregating all data.
Hard-coded Sleep Intervals: Using time.sleep(2) extensively can slow down your script execution unnecessarily if the page loads faster. Consider using WebDriverWait for more efficient waiting.
Potential XPath/CSS Selector Issues: Ensure the CSS selectors you are using match the website's HTML structure, as the structure might change, leading to NoSuchElementException.
Image Download: You are downloading images based on a string comparison with fuzz.WRatio. Ensure this logic accurately captures the images you're interested in.
Here's a revised version focusing on fixing the above:
python
import os
import shutil
import time
from urllib.parse import urljoin
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
from fuzzywuzzy import fuzz
import requests
BOOKS_COVERS_PATH = 'path_to_covers' # Define appropriately
LIVELIB_BASE_URL = 'https://www.livelib.ru'
def get_books_sel(pages_count=1):
# Удаляем старую папку с обложками и создаем новую
if os.path.exists(BOOKS_COVERS_PATH):
shutil.rmtree(BOOKS_COVERS_PATH)
os.mkdir(BOOKS_COVERS_PATH)
# Загружаем авторов из CSV файла
authors_df = pd.read_csv("authors.csv", delimiter=";")
authors = authors_df.to_dict('records')
books_counter = 0
all_books = []
all_genres = []
all_books_genres = []
# Настройка Selenium
options = Options()
options.add_argument('--headless') # Запуск в фоновом режиме
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
for author in authors:
books_url = urljoin(LIVELIB_BASE_URL, f"/author/{author['Link'].split('/')[-1].split('-')[0]}/top/work/listview/biglist/~")
for i in range(1, pages_count + 1):
driver.get(books_url + f"{i}")
time.sleep(2) # Consider replacing with a more efficient wait strategy
names = driver.find_elements(By.CSS_SELECTOR, "ul#author-objects li")
for index, name in enumerate(names):
title = name.find_element(By.CSS_SELECTOR, "a.book-item__title").text
print(title)
# Получаем детальную информацию о книге
book_detail_url = urljoin(LIVELIB_BASE_URL, name.find_element(By.CSS_SELECTOR, "a.book-item__title").get_attribute("href"))
driver.get(book_detail_url)
print(book_detail_url)
time.sleep(2)
try:
annotation = driver.find_element(By.CSS_SELECTOR, "summary.bc-card__text-block-txt.ugc-content").text
except:
annotation = ""
genres_tags = driver.find_elements(By.CSS_SELECTOR, "a.bc-info__link.bc-info__link_type_category")
for genre in genres_tags:
genre_title = genre.text.replace("№2 в ", "").strip()
genre_id = next((gen["Id"] for gen in all_genres if gen['Title'] == genre_title), None)
if genre_id is None:
all_genres.append({"Id": len(all_genres), "Title": genre_title})
genre_id = len(all_genres) - 1
all_books_genres.append({"Book_id": books_counter, "Genre_id": genre_id})
labi_url = f"https://www.labirint.ru/search/{author['Author'].replace(' ', '%20')}%20{title.replace(' ', '%20')}/?stype=0"
driver.get(labi_url)
time.sleep(2)
try:
image = driver.find_element(By.CSS_SELECTOR, "div.product-card img")
img_ratio = fuzz.WRatio(image.get_attribute("title"), f"{author['Author']} {title}")
print(img_ratio)
if img_ratio > 80:
img_path = os.path.join(BOOKS_COVERS_PATH, os.path.basename(image.get_attribute("data-src")) + ".webp")
with open(img_path, "wb") as f:
f.write(requests.get(image.get_attribute("data-src")).content)
else:
img_path = os.path.join(BOOKS_COVERS_PATH, f"{books_counter}_{os.path.basename(name.find_element(By.CSS_SELECTOR, 'img').get_attribute('data-pagespeed-lazy-src'))}")
with open(img_path, "wb") as f:
f.write(requests.get(name.find_element(By.CSS_SELECTOR, "img").get_attribute('data-pagespeed-lazy-src')).content)
except Exception as e:
print(f"Error downloading image: {e}")
img_path = ""
all_books.append({
"Id": books_counter,
"Title": title,
"Avatar": img_path,
})
books_counter += 1
driver.quit()
df = pd.DataFrame(all_books)
df.to_csv("books.csv", sep=';', encoding='utf-8', index=False)
df.to_excel("books.xlsx", index=False)
df = pd.DataFrame(all_genres)
df.to_csv("genres.csv", sep=';', encoding='utf-8', index=False)
df.to_excel("genres.xlsx", index=False)
df = pd.DataFrame(all_books_genres)
df.to_csv("books_genres.csv", sep=';', encoding='utf-8', index=False)
df.to_excel("books_genres.xlsx", index=False)
print(all_books)
print(all_genres)
print(all_books_genres)
# Example call
# get_books_sel(pages_count=2)
Make sure to replace 'path_to_covers' with the actual path where you want to save the book covers. Adjust other constants like LIVELIB_BASE_URL as necessary.