File size: 9,042 Bytes
4aa3246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import pandas as pd\n",
    "import os\n",
    "import logging\n",
    "import csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class GoodReadsScrapper:\n",
    "    def __init__(self) -> None:\n",
    "        self.BASE_URL = 'https://www.goodreads.com/shelf/show/{}'\n",
    "        self.GENRE_URL = 'https://www.goodreads.com/genres/list?page={}'\n",
    "        self.GOOD_READS_URL = 'https://www.goodreads.com{}'\n",
    "        self.CURRENT_INDEX = 0\n",
    "    \n",
    "    def scrape_genres(self,filename='genres.txt'):\n",
    "        if os.path.exists(filename):\n",
    "            with open(filename, 'r') as file:\n",
    "                genres = [line.strip() for line in file.readlines()]\n",
    "            print(\"Genres loaded from file.\")\n",
    "        else:\n",
    "            page = 1\n",
    "            genres = []\n",
    "\n",
    "            while True:\n",
    "                url = self.GENRE_URL.format(page)\n",
    "                response = requests.get(url)\n",
    "\n",
    "                if response.status_code == 200:\n",
    "                    soup = BeautifulSoup(response.text, 'html.parser')\n",
    "                    container_div = soup.find('div', {'class': 'leftContainer'})\n",
    "                    genre_divs = container_div.find_all('div', {'class': 'left'})\n",
    "                    for genre_div in genre_divs:\n",
    "                        genre = genre_div.find('a', {'class': 'mediumText actionLinkLite'})\n",
    "                        if genre:\n",
    "                            genre_text = genre.text.strip()\n",
    "                            genres.append(genre_text)\n",
    "                            print(\"Scrapped genre is:\", genre_text)\n",
    "\n",
    "                    next_page_link = soup.find('a', {'class': 'next_page'})\n",
    "                    if next_page_link is None:\n",
    "                        break\n",
    "\n",
    "                page += 1\n",
    "\n",
    "            with open(filename, 'w') as file:\n",
    "                for genre in genres:\n",
    "                    file.write(genre + '\\n')\n",
    "            print(\"Genres saved to file.\")\n",
    "\n",
    "        return genres\n",
    "    \n",
    "    def scrape_book(self,genre: str, csv_index: int):\n",
    "        response = requests.get(self.BASE_URL.format(genre))\n",
    "        \n",
    "        if response.status_code == 200:\n",
    "            soup = BeautifulSoup(response.text, 'html.parser')\n",
    "            container_div = soup.find('div', {'class': 'leftContainer'}) \n",
    "            book_divs = container_div.findAll('div', {'class': 'elementList'})\n",
    "            \n",
    "            for book_div in book_divs:\n",
    "                link = book_div.find('div', {'class': 'left'}).find('a', {'class': 'leftAlignedImage'})['href']\n",
    "                self.CURRENT_INDEX += 1\n",
    "                \n",
    "                if self.CURRENT_INDEX <= csv_index:\n",
    "                    continue\n",
    "                \n",
    "                self.scrape_x_book(link,self.CURRENT_INDEX)\n",
    "    \n",
    "    def scrape_x_book(self,book_url: str, i: int):\n",
    "        try:\n",
    "            response = requests.get(self.GOOD_READS_URL.format(book_url))\n",
    "\n",
    "            if response.status_code != 200:\n",
    "                logging.error(f\"Failed to fetch {book_url}. Status code: {response.status_code}\")\n",
    "                return\n",
    "\n",
    "            soup = BeautifulSoup(response.text, 'html.parser')\n",
    "\n",
    "            main_content = soup.find('div', {'class': 'BookPage__mainContent'})\n",
    "\n",
    "            # Get title\n",
    "            title = main_content.find('div', {'class': 'BookPageTitleSection'}).find('div', {'class': 'BookPageTitleSection__title'}).find('h1', {'class': 'Text Text__title1'}).text.strip()\n",
    "\n",
    "            # Metadata\n",
    "            metadata_section = main_content.find('div', {'class': 'BookPageMetadataSection'})\n",
    "\n",
    "            # Author\n",
    "            author = metadata_section.find('div', {'class': 'BookPageMetadataSection__contributor'}).find('span', {'class': 'ContributorLink__name'}).text.strip()\n",
    "\n",
    "            # Rating\n",
    "            rating = metadata_section.find('div', {'class': 'BookPageMetadataSection__ratingStats'}).find('div', {'class': 'RatingStatistics__column'}).find('div', {'class': 'RatingStatistics__rating'}).text.strip()\n",
    "\n",
    "            # Description\n",
    "            description = metadata_section.find('div', {'class': 'BookPageMetadataSection__description'}).find('div', {'class': 'TruncatedContent'}).find('span', {'class': 'Formatted'}).text.strip()\n",
    "\n",
    "            # Genres List\n",
    "            genres_list = []\n",
    "            genre_div = metadata_section.find('div', {'class': 'BookPageMetadataSection__genres'}).find('ul', {'class': 'CollapsableList'}).findAll('span', {'class': 'BookPageMetadataSection__genreButton'})\n",
    "\n",
    "            for genre in genre_div:\n",
    "                g = genre.find('span', {'class': 'Button__labelItem'}).text.strip()\n",
    "                genres_list.append(g)\n",
    "\n",
    "            # Get Reviews\n",
    "            reviews = []\n",
    "            reviews_section = soup.find('div', {'class': 'ReviewsSection'}).findAll('div', {'class': 'ReviewsList'})\n",
    "            articles = reviews_section[1].findAll('article', {'class': 'ReviewCard'})\n",
    "\n",
    "            for article in articles:\n",
    "                review_text = article.find('section', {'class': 'ReviewText'}).find('span', {'class': 'Formatted'}).text.strip()\n",
    "                reviews.append(review_text)\n",
    "\n",
    "            # Write to CSV\n",
    "            csv_filename = 'book_data.csv'\n",
    "            with open(csv_filename, 'a', newline='', encoding='utf-8') as csvfile:\n",
    "                fieldnames = ['Id', 'Title', 'Author', 'Rating', 'Description', 'Genres', 'Reviews']\n",
    "                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n",
    "\n",
    "                # If the file is empty, write the header\n",
    "                if csvfile.tell() == 0:\n",
    "                    writer.writeheader()\n",
    "\n",
    "                writer.writerow({\n",
    "                    'Id': i,\n",
    "                    'Title': title,\n",
    "                    'Author': author,\n",
    "                    'Rating': rating,\n",
    "                    'Description': description,\n",
    "                    'Genres': ', '.join(genres_list),\n",
    "                    'Reviews': '\\n'.join(reviews)\n",
    "                })\n",
    "\n",
    "            # Log the processed book\n",
    "            print(f\"Processed book: {title} \\nRecord: {i}\")\n",
    "\n",
    "        except Exception as e:\n",
    "            logging.error(f\"Error processing book {i}: {e}\")\n",
    "            # Optionally, you can log the error and continue to the next book\n",
    "\n",
    "    def get_last_processed_id(self, csv_filename='book_data.csv'):\n",
    "        try:\n",
    "            if os.path.exists(csv_filename):\n",
    "                df = pd.read_csv(csv_filename)\n",
    "                if not df.empty and 'Id' in df.columns:\n",
    "                    return df['Id'].max()\n",
    "        except pd.errors.EmptyDataError:\n",
    "            # Handle the case where the file is empty\n",
    "            return 0\n",
    "        except Exception as e:\n",
    "            # Handle other exceptions\n",
    "            print(f\"Error reading CSV file: {e}\")\n",
    "        \n",
    "        return 0\n",
    "    \n",
    "    def main(self):\n",
    "        genres = self.scrape_genres()\n",
    "        last_processed_id = self.get_last_processed_id()\n",
    "        for genre in genres:\n",
    "            self.scrape_book(genre, last_processed_id)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scrapper = GoodReadsScrapper()\n",
    "scrapper.main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}