I have made the following program to gather data on random books from Goodreads, via their random books feature.
import requests
import re
URL = "https://www.goodreads.com/book/random"
while True:
html_text = requests.get(URL).text
# Rating Count
bg_rating_count = html_text.find("<span class=\"value-title\" title=\"") + 33
end_rating_count = html_text.find("\" itemprop=\"ratingCount\">", bg_rating_count)
rating_count = int(html_text[bg_rating_count : end_rating_count].replace(',', ''))
if rating_count >= 30:
if "<span itemprop=\"numberOfPages\">" in html_text:
# Title
bg_title = html_text.find("<meta property=\"og:title\" content=\"") + 35
end_title = html_text.find("\"/>", bg_title)
title = html_text[bg_title : end_title].replace("&", '&')
title = re.sub(r'\((.*)\)','', title)
# Pages
bg_pages = html_text.find("<span itemprop=\"numberOfPages\">") + 31
end_pages = html_text.find(" page", bg_pages)
pages = int(html_text[bg_pages : end_pages])
# Rating
bg_rating = html_text.find("<span class=\"average\" itemprop=\"ratingValue\">") + 45
end_rating = html_text.find("</", bg_rating)
rating = float(html_text[bg_rating : end_rating])
if pages != 0:
print(title, pages, rating, sep='\t')
This is my first time working with anything of this sort, and I am still learning Python as I go. Here's a breakdown of what the code does (or, is intended to do):
This program gets the HTML code from a random book via the
URL
.Finds the book's rating count by searching for a specific HTML tag. Removes any commas in the rating number before making sure it's an integer.
If the rating count is >= 30, it accepts it and continues to gather data. Otherwise it moves on and tries another random book.
If it passes the rating count test, it checks whether it has a listed number of pages. If it does, it continues to gather data. Otherwise it moves on and tries another random book.
If it passes the page count test, it then gathers the title. If the title has an ampersand HTML code
&
it replaces it with the actual ampersand character&
. As well, if the title contains text identifying a series, it removes the series text. Here's an example of what I'm talking about, where it says(The Hunger Games #1)
. I am new to regex, let me know if I am doing anything horrible.It then actually gathers the page count along with making sure it's an integer, and the book's rating with making sure it's a float.
If the page count is not 0 (which is sometimes the case for ill-detailed books), it then prints out the relevant data in a tab-separated format that I can copy-paste for later.
I understand that this program goes on forever, and I intended it like that. This program is meant to be manually used, and I halt it when I am done.
Is multi-threading a good idea? How can I improve this code, both in terms of performance, readability, or code logic?