-
-
Save tupaschoal/625115d65859f9efaf84a8612985cf61 to your computer and use it in GitHub Desktop.
Script created to programatically navigate Skoob fetching a user's bookshelf and the gender distribution of the books they have read
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| This is a basic script that scrapes a user profile on Skoob for all the books they have read | |
| to fetch their names and some basic statistics | |
| """ | |
| import json | |
| import os | |
| import time | |
| from typing import NamedTuple | |
| from selenium import webdriver | |
| from selenium.webdriver.common.by import By | |
| from selenium.webdriver.common.keys import Keys | |
| from selenium.webdriver.support.ui import WebDriverWait | |
| from selenium.webdriver.support import expected_conditions as EC | |
| from selenium.common.exceptions import TimeoutException | |
| READ_BOOKS_PAGES_FILE = "read_books_pages.json" | |
| READ_BOOKS_STATISTICS_FILE = "read_books_statistics.json" | |
| # Set your Skoob credentials | |
| SKOOB_USERNAME = "" | |
| SKOOB_PASSWORD = "" | |
| def login_skoob(driver, username, password): | |
| """ Go to the Skoob login page and log in """ | |
| driver.get("https://www.skoob.com.br/login/") | |
| login_form = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "UsuarioEmail"))) | |
| login_form.send_keys(username) | |
| driver.find_element(By.ID, "UsuarioSenha").send_keys(password) | |
| driver.find_element(By.XPATH, "//input[@value=' Entrar ']").send_keys(Keys.ENTER) | |
| # Wait until the summary of the user appears on the page, which confirms the login | |
| WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, "livro-perfil-status02"))) | |
| def fetch_read_books(driver): | |
| """ Given a browser with a logged in user, fetch all the books they have read """ | |
| # TODO: Unhardcode user id | |
| driver.get("https://www.skoob.com.br/estante/livros/1/2599") | |
| # When first book appears, page has been fully loaded | |
| WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".livro-capa"))) | |
| read_book_pages = [] | |
| old_page_content = None | |
| while True: | |
| book_links = driver.find_elements(By.CSS_SELECTOR, ".livro-capa") | |
| read_book_pages.extend([elem.find_element(By.TAG_NAME, "a").get_attribute('href') for elem in book_links]) | |
| old_page_content = driver.page_source | |
| next_page_button = driver.find_element(By.XPATH, "//*[contains(text(), '›')]") | |
| next_page_button.click() | |
| # Didn't find proper way to check whether page had been rightfully loaded, using sleep 🤡 | |
| # TODO: Stop using sleep here | |
| time.sleep(2) | |
| # TODO: Find better way to stop switching pages than comparing whole HTML for changes | |
| new_page_content = driver.page_source | |
| if new_page_content == old_page_content: | |
| break | |
| return read_book_pages | |
| class BookStatistics(NamedTuple): | |
| """ Utility class to aggregate book statistics """ | |
| name: str | |
| number_readers: int | |
| percentage_male: int | |
| percentage_female: int | |
| def fetch_book_stats(driver, read_book_pages): | |
| """ Given a list of skoob webpages, return the BookStatistics associated with it """ | |
| book_stats = [] | |
| for book_page in read_book_pages: | |
| driver.get(book_page) | |
| # Fetch number of readers, sadly sometimes this is not loaded fast enough to be stored correctly | |
| # TODO: Wait for proper page loading to get this data | |
| readers = 0 | |
| read_elements = driver.find_elements(By.XPATH, "//a[contains(@href,'/livro/leitores/leram/')]") | |
| for read_element in read_elements: | |
| if read_element.get_attribute('class') == "text_blue": | |
| readers = read_element.text | |
| break | |
| book_stats.append( | |
| BookStatistics( | |
| name = driver.title, | |
| number_readers = readers, | |
| percentage_male = driver.find_element(By.CLASS_NAME, "pg-livro-icone-male-label").text, | |
| percentage_female = driver.find_element(By.CLASS_NAME, "pg-livro-icone-female-label").text, | |
| ) | |
| ) | |
| return book_stats | |
| def fetch(cache_location, function, *args): | |
| """ Fetches information from cache_location, if it exists, otherwise calls function to retrieve """ | |
| if os.path.exists(cache_location): | |
| with open(cache_location, 'r', encoding="utf-8") as file_cache: | |
| fetched_info = json.load(file_cache) | |
| else: | |
| fetched_info = function(*args) | |
| with open(cache_location, 'w', encoding="utf-8") as file_cache: | |
| json.dump(fetched_info, file_cache) | |
| return fetched_info | |
| def get_book_statistics_from_skoob(): | |
| DRIVER = None | |
| try: | |
| # Only start browser if cached information does not exist | |
| if not os.path.exists(READ_BOOKS_PAGES_FILE) or not os.path.exists(READ_BOOKS_STATISTICS_FILE): | |
| DRIVER = webdriver.Firefox() | |
| login_skoob(DRIVER, SKOOB_USERNAME, SKOOB_PASSWORD) | |
| read_book_pages_data = fetch(READ_BOOKS_PAGES_FILE, fetch_read_books, DRIVER) | |
| book_statistics_data = fetch(READ_BOOKS_STATISTICS_FILE, fetch_book_stats, DRIVER, read_book_pages_data) | |
| except TimeoutException: | |
| print("Timed out waiting for page to load") | |
| finally: | |
| if DRIVER: | |
| DRIVER.quit() | |
| return book_statistics_data | |
| book_statistics = get_book_statistics_from_skoob() | |
| # Convert back to Named tuple | |
| book_statistics_typed = [BookStatistics._make(book) for book in book_statistics] | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| from matplotlib import colors | |
| from matplotlib.ticker import PercentFormatter | |
| # :-1 to remove the % sign at the end | |
| female_percentages_all = [int(book.percentage_female[:-1]) for book in book_statistics_typed] | |
| female_percentages_five_readers = [int(book.percentage_female[:-1]) for book in book_statistics_typed if int(book.number_readers.replace('.', '')) > 4] | |
| female_percentages_ten_readers = [int(book.percentage_female[:-1]) for book in book_statistics_typed if int(book.number_readers.replace('.', '')) > 9] | |
| fig, axs = plt.subplots(1, 3, sharey=True, sharex=True, tight_layout=True) | |
| axs[0].grid(axis='x', zorder=0) | |
| axs[0].set_xticks([0, 25, 50, 75, 100]) | |
| axs[0].hist(female_percentages_all, bins=30, color='skyblue', edgecolor='black', zorder=1) | |
| axs[0].set_title("Todos os Livros") | |
| axs[1].grid(axis='x', zorder=0) | |
| axs[1].hist(female_percentages_five_readers, bins=30, color='skyblue', edgecolor='black') | |
| axs[1].set_title("Livros (5+ leitores)") | |
| axs[2].grid(axis='x', zorder=0) | |
| axs[2].hist(female_percentages_ten_readers, bins=30, color='skyblue', edgecolor='black') | |
| axs[2].set_title("Livros (10+ leitores)") | |
| plt.axis([0, 100, 0, plt.ylim()[1]]) | |
| fig.add_subplot(111, frameon=False) | |
| # hide tick and tick label of the big axis | |
| plt.tick_params(labelcolor='none', which='both', top=False, bottom=False, left=False, right=False) | |
| plt.xlabel("Leitoras (%)") | |
| plt.ylabel("Número de livros") | |
| plt.show() | |
| def get_num_readers(str_num_readers): | |
| return int(str_num_readers.replace('.', '')) | |
| def most_gender_book(num_readers): | |
| most_male_book = ("", 0) | |
| most_female_book = ("", 0) | |
| for book in book_statistics_typed: | |
| if get_num_readers(book.number_readers) >= num_readers: | |
| if int(book.percentage_female[:-1]) >= most_female_book[1]: | |
| most_female_book = (book.name, int(book.percentage_female[:-1])) | |
| if int(book.percentage_male[:-1]) > most_male_book[1]: | |
| most_male_book = (book.name, int(book.percentage_male[:-1])) | |
| return (most_female_book, most_male_book) | |
| most_pairs = [(num, most_gender_book(num)) for num in [10, 100, 500, 760, 980, 1000, 1800, 2500, 10000, 11000, 12000, 50000, 100000, 250000, 500000, 750000]] | |
| print("|Number of readers|Mostly read by women|Mostly read by men|") | |
| print("|---|---|---|") | |
| for pair in most_pairs: | |
| print(f"|{pair[0]}|{pair[1][0][1]}%: {pair[1][0][0]}|{pair[1][1][1]}%: {pair[1][1][0]}|") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment