Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
279 changes: 272 additions & 7 deletions lab-web-scraping.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,281 @@
"You can choose another website that interests you and is suitable for scraping data. Options like Wikipedia, The New York Times, or even library databases are great alternatives. The main goal remains the same: extract useful data and enhance your web scraping skills while exploring a source of information you enjoy. This is your opportunity to practice and adapt to different web environments!"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cd2fc7bc",
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"from bs4 import BeautifulSoup\n",
"\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "b476dff2",
"metadata": {},
"outputs": [],
"source": [
"url = \"https://books.toscrape.com/catalogue/page-1.html\"\n",
"response = requests.get(url)\n",
"\n",
"soup = BeautifulSoup(response.content)\n",
"\n",
"#identify the grid\n",
"grid = soup.find(\"ol\", attrs = {\"class\":\"row\"})\n",
"\n",
"#within the grid, identify all books\n",
"books = grid.find_all(\"article\", attrs = {\"class\":\"product_pod\"})"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "cb6acac7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Three'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#title\n",
"books[0].find_all(\"a\")[-1][\"title\"]\n",
"\n",
"#price\n",
"books[0].find(\"p\", attrs = {\"class\":\"price_color\"}).get_text()\n",
"\n",
"#rating\n",
"books[0].find(\"p\", attrs = {\"class\":\"star-rating\"})[\"class\"][-1]"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "d44c2dbe",
"metadata": {},
"outputs": [],
"source": [
"def get_title(book):\n",
" return book.find_all(\"a\")[-1][\"title\"]\n",
"\n",
"def get_price(book):\n",
" raw_price = book.find(\"p\", attrs = {\"class\":\"price_color\"}).get_text()\n",
" clean_price = float(raw_price.replace(\"£\", \"\"))\n",
" return float(clean_price)\n",
"\n",
"def get_rating(book):\n",
" raw_rating = book.find(\"p\", attrs = {\"class\":\"star-rating\"})[\"class\"][-1]\n",
" if raw_rating == \"One\":\n",
" return 1\n",
" elif raw_rating == \"Two\":\n",
" return 2\n",
" elif raw_rating == \"Three\":\n",
" return 3\n",
" elif raw_rating == \"Four\":\n",
" return 4\n",
" else:\n",
" return 5\n",
" \n",
"def get_link(book):\n",
" domain = \"https://books.toscrape.com/catalogue/\"\n",
" href = book.find_all(\"a\")[-1][\"href\"]\n",
"\n",
" return domain + href\n",
"\n",
"\n",
"def get_upc(soup_book):\n",
" upc = soup_book.find(\"td\").get_text()\n",
" return upc\n",
"\n",
"\n",
"def get_availability(soup_book):\n",
" return soup_book.find(\"p\", attrs={\"class\":\"instock availability\"}).get_text().strip()\n",
"\n",
"def get_description(soup_book):\n",
" return soup_book.find(\"div\", id=\"product_description\").find_next(\"p\").get_text().strip()\n",
"\n",
"def get_genre(soup_book):\n",
" return soup_book.find(\"ul\", attrs = {\"class\":\"breadcrumb\"}).find_all(\"li\")[-2].get_text().strip()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "ee34e3eb",
"metadata": {},
"outputs": [],
"source": [
"def scrape_books(max_price, min_rating, page_number):\n",
"\n",
" url = f\"https://books.toscrape.com/catalogue/page-{page_number}.html\"\n",
" response = requests.get(url)\n",
"\n",
" soup = BeautifulSoup(response.content)\n",
"\n",
" #identify the grid\n",
" grid = soup.find(\"ol\", attrs = {\"class\":\"row\"})\n",
"\n",
" #within the grid, identify all books\n",
" books = grid.find_all(\"article\", attrs = {\"class\":\"product_pod\"})\n",
"\n",
" dict = {}\n",
" index = 0\n",
"\n",
" for book in books:\n",
" title = get_title(book)\n",
" price = get_price(book)\n",
" rating = get_rating(book)\n",
" book_url = get_link(book)\n",
"\n",
"\n",
"\n",
" if max_price >= price and min_rating <= rating:\n",
" #if both conditions above are met, we need to extract more data (UPC, Genre, etc)\n",
" r_book = requests.get(book_url)\n",
" soup_book = BeautifulSoup(r_book.content)\n",
"\n",
" #extra fields to scrap\n",
" upc = get_upc(soup_book)\n",
" availability = get_availability(soup_book)\n",
" description = get_description(soup_book)\n",
" genre = get_genre(soup_book)\n",
"\n",
"\n",
" dict[index] = {\"title\": title,\n",
" \"price\":price,\n",
" \"rating\":rating,\n",
" \"url\": book_url,\n",
" \"upc\":upc,\n",
" \"availability\": availability,\n",
" \"description\":description,\n",
" \"genre\": genre}\n",
" \n",
" index +=1\n",
" else:\n",
" pass\n",
"\n",
" return pd.DataFrame.from_dict(dict, orient = \"index\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "40359eee-9cd7-4884-bfa4-83344c222305",
"metadata": {
"id": "40359eee-9cd7-4884-bfa4-83344c222305"
},
"id": "e938cd3b",
"metadata": {},
"outputs": [],
"source": [
"max_price = 20\n",
"min_rating = 4\n",
"\n",
"list_of_dfs = []\n",
"for i in range(1, 51):\n",
" df = scrape_books(max_price= max_price, \n",
" min_rating= min_rating, \n",
" page_number=i)\n",
" \n",
" list_of_dfs.append(df)\n",
" print(f\"Scraping page number {i}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c5feeb55",
"metadata": {},
"outputs": [],
"source": [
"full_df = pd.concat(list_of_dfs, ignore_index=True)\n",
"full_df"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "7cd1970d",
"metadata": {},
"outputs": [],
"source": [
"#alternative -> for loop inside the function\n",
"\n",
"def scrape_books(max_price, min_rating):\n",
"\n",
" list_of_dfs = []\n",
" for page_number in range(1, 51):\n",
"\n",
" url = f\"https://books.toscrape.com/catalogue/page-{page_number}.html\"\n",
" response = requests.get(url)\n",
"\n",
" soup = BeautifulSoup(response.content)\n",
"\n",
" #identify the grid\n",
" grid = soup.find(\"ol\", attrs = {\"class\":\"row\"})\n",
"\n",
" #within the grid, identify all books\n",
" books = grid.find_all(\"article\", attrs = {\"class\":\"product_pod\"})\n",
"\n",
" dict = {}\n",
" index = 0\n",
"\n",
" for book in books:\n",
" title = get_title(book)\n",
" price = get_price(book)\n",
" rating = get_rating(book)\n",
" book_url = get_link(book)\n",
"\n",
"\n",
"\n",
" if max_price >= price and min_rating <= rating:\n",
" #if both conditions above are met, we need to extract more data (UPC, Genre, etc)\n",
" r_book = requests.get(book_url)\n",
" soup_book = BeautifulSoup(r_book.content)\n",
"\n",
" #extra fields to scrap\n",
" upc = get_upc(soup_book)\n",
" availability = get_availability(soup_book)\n",
" description = get_description(soup_book)\n",
" genre = get_genre(soup_book)\n",
"\n",
"\n",
" dict[index] = {\"title\": title,\n",
" \"price\":price,\n",
" \"rating\":rating,\n",
" \"url\": book_url,\n",
" \"upc\":upc,\n",
" \"availability\": availability,\n",
" \"description\":description,\n",
" \"genre\": genre}\n",
" \n",
" index +=1\n",
" else:\n",
" pass\n",
"\n",
" page_df = pd.DataFrame.from_dict(dict, orient = \"index\")\n",
" list_of_dfs.append(page_df)\n",
"\n",
" return pd.concat(list_of_dfs, ignore_index=True)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b3f031fb",
"metadata": {},
"outputs": [],
"source": [
"# Your solution goes here"
"scrape_books(20, 4)"
]
}
],
Expand All @@ -126,7 +391,7 @@
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -140,7 +405,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.5"
}
},
"nbformat": 4,
Expand Down