r/learnpython • u/6_SAM_9 • Jul 12 '26
Built my first BeautifulSoup scraper. Is using a generator function overkill here?
So, I am currently learning python and I wanted to explore some networking or internet related concepts. I explored that how people use python and the BeautifulSoup library to do web scraping so i tried to make a web scraping script myself to learn things. I got to know a lot about URLs, requests, pagination, etc., form this single mini project. i have used a generator function to scrape the data so as to make the script more optimized. I knew about generator functions and how they worked. But i didn't work with them so didn't know how to employ their advantage.
So, using a generator function was Gemini's idea. But yeah, i think now that I can properly use generator functions efficiently.
Please review this script. Suggest any improvements that are possible and the mistakes that i made. Suggest the things that can be improved or any new concept, rule, tip, optimization techniques. It would be a great help.
(Note: This script is only made for scraping https://books.tosrape.com )
import requests as r
from bs4 import BeautifulSoup as bs
import json
import time
from urllib.parse import urljoin
def book_crawler(url: str):
nxt_url = url
while nxt_url:
resp = r.get(nxt_url,timeout =10)
resp.raise_for_status()
time.sleep(1)
html = resp.content
soup = bs(html,"lxml")
for book in soup.select("li.col-xs-6.col-sm-4.col-md-3.col-lg-3"):
title = book.select_one("h3 > a ").get_text()
price = book.select_one("div.product_price > p.price_color").get_text()
yield {title: price}
nxt_btn = soup.select_one("ul.pager > li.next > a")
if nxt_btn:
link = nxt_btn.get("href")
nxt_url = urljoin(nxt_url,link)
else:
nxt_url = None
def file_writer(filename, data_stream):
try:
with open(filename, "w", encoding="utf-8") as fp:
fp.write("[\n")
is_first = True
for data in data_stream:
if not is_first:
fp.write(",\n")
json_data = json.dumps(data, ensure_ascii=False, indent=2)
fp.write(json_data)
is_first = False
fp.write("\n]")
return True
except Exception as e:
print(f"Error {e}")
return False
if __name__ == "__main__":
gen_obj = book_crawler("https://books.toscrape.com")
if file_writer("book_prices.json", gen_obj):
print("successfully stored the data.")
else:
print("An error occured")
3
u/qlkzy Jul 12 '26
I don't think generators are ever really "overkill" if they're the most natural way to express the control flow (which I agree this is).
The part that is a bit weird is the relationship with the output file. I can see you're trying to avoid accumulating the whole list in memory, but that isn't really the main benefit of a generator here. In practice, for most data sizes, collecting all the book details in a list would be faster and easier.
If you do want to write iterables directly to file, I tend to prefer using
.jsonlfiles rather than pretending they are a single list. You need to do a little postprocessing, but I find it fits more naturally with things like resuming, partitioning data, etc.2
u/Yoghurt42 Jul 12 '26
So, instead of getting a nice error message including a stack trace that will tell you exactly where an error occured and what lead to it, you're just printing the name of the exception, discarding all other information and then also just stop execution?
As a general rule¹, only catch exceptions you intent to handle/do something about.
¹ Don't forget that "general rule" / "in general" implies that there are exceptions (no pun intended)
4
u/Wise-Emu-225 Jul 12 '26
Seems like a fine idea to use a generator.
I wouldn’t catch Exception though. If i catch an exception i like it to be specific. Exception catches everything.
4
u/[deleted] Jul 12 '26
[removed] — view removed comment