When a site offers no API, web scraping extracts data straight from its HTML. The pattern is two steps: requests fetches the page, and BeautifulSoup parses the HTML so you can select the elements you want.
Fetch & select
Use CSS selectors to locate elements, then read their text or attributes:
import requestsfrom bs4 import BeautifulSouphtml = requests.get("https://example.com", timeout=10).textsoup = BeautifulSoup(html, "html.parser")for card in soup.select("div.product"): # CSS selectortitle = card.select_one("h2.title").get_text(strip=True)price = card.select_one(".price").get_text(strip=True)link = card.select_one("a")["href"] # an attributeprint(title, price, link)
Scrape responsibly
Key takeaways
- 01requests fetches the HTML; BeautifulSoup parses and selects elements.
- 02CSS selectors (select / select_one) locate data; get_text() and [attr] read it.
- 03Respect robots.txt, terms of service, and rate limits; identify your bot.
- 04BeautifulSoup sees only initial HTML — JS-rendered pages need browser automation.
- 05Always prefer an official API when one is available.
