Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟡 Advanced Python  ·  Lesson 27

Web Scraping Basics in Python

In this lesson: Scrape web pages in Python using requests and HTML parsing — basics, ethics and a simple working example. In Hindi & English.

What is web scraping?

Web scraping means a program downloads a web page and pulls out the information you need – prices, titles, tables, links – instead of copying it by hand. Python is the most popular language for it because of two libraries: requests (download the page) and BeautifulSoup (find things inside the HTML).

StepTool
1. Check you are allowed (terms, robots.txt, API available?)Browser, urllib.robotparser
2. Download the HTMLrequests.get()
3. Parse and find elementsBeautifulSoup, CSS selectors
4. Clean and savecsv, json, pandas
5. Be politeDelay between requests, identify yourself
Terminal
pip install requests beautifulsoup4
⚖️ Legal and ethical rules first

Scrape only public data, respect the website’s terms and robots.txt, never collect personal data (phone numbers, emails) without permission, do not bypass logins or CAPTCHAs, and keep a delay so you do not overload the server. If the site offers an API, use the API.

Step 1: parse HTML with BeautifulSoup

Practise on a small HTML file first. Save this as price_list.html:

HTML – price_list.html
<html><body>
  <h1>Sharma Sweets – Price List</h1>
  <table id="prices">
    <tr><th>Sweet</th><th>Price</th><th>Stock</th></tr>
    <tr class="item"><td>Kaju Katli</td><td>₹900/kg</td><td>Yes</td></tr>
    <tr class="item"><td>Ghewar</td><td>₹650/kg</td><td>Yes</td></tr>
    <tr class="item sold"><td>Kalakand</td><td>₹600/kg</td><td>No</td></tr>
  </table>
  <a href="/order">Order online</a> <a href="https://wa.me/919829012345">WhatsApp</a>
</body></html>
Python – parse_local.py
from bs4 import BeautifulSoup

with open("price_list.html", encoding="utf-8") as f:
    soup = BeautifulSoup(f.read(), "html.parser")

print(soup.h1.get_text(strip=True))              # first <h1>
print(soup.find("td").text)                      # first <td>
print(len(soup.find_all("tr", class_="item")), "items")

for row in soup.find_all("tr", class_="item"):
    name, price, stock = [td.get_text(strip=True) for td in row.find_all("td")]
    print(f"{name:<11} {price:<9} in stock: {stock}")
Sharma Sweets – Price List Kaju Katli 3 items Kaju Katli ₹900/kg in stock: Yes Ghewar ₹650/kg in stock: Yes Kalakand ₹600/kg in stock: No

Step 2: CSS selectors with select()

If you know CSS, select() and select_one() are the fastest way to find elements. Right-click an element in Chrome → Inspect to see its tags and classes.

Python – css_selectors.py
from bs4 import BeautifulSoup

soup = BeautifulSoup(open("price_list.html", encoding="utf-8").read(), "html.parser")

print([td.text for td in soup.select("#prices tr.item td:first-child")])
print(soup.select_one("tr.sold td").text, "is sold out")
for a in soup.select("a[href]"):
    print(a.text, "→", a["href"])
['Kaju Katli', 'Ghewar', 'Kalakand'] Kalakand is sold out Order online → /order WhatsApp → https://wa.me/919829012345
SelectorFinds
h2all h2 tags
.priceclass="price"
#pricesid="prices"
table tr.itemtr with class item inside a table
a[href]links that have an href
td:first-childfirst cell of each row

Step 3: scrape a real page

Now download a real page – the lesson list of this Python course – and extract every lesson link. (Scraping CodingEasily for learning is allowed.)

Python – scrape_lessons.py
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

URL = "https://codingeasily.in/tutorial/python/"
headers = {"User-Agent": "StudentScraper/1.0 (learning project)"}

r = requests.get(URL, headers=headers, timeout=10)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")

links = soup.select("a.topic-card-link")
print("lessons found:", len(links))
for a in links[:5]:
    title = a.select_one(".name.english-content").get_text(strip=True)
    print("-", title, "→", urljoin(URL, a["href"]))
lessons found: 66 - Introduction to Python → https://codingeasily.in/tutorial/python/python-introduction/ - Python Setup: Windows, VS Code and IDLE → https://codingeasily.in/tutorial/python/setup-python/ - First Python Program: Hello World → https://codingeasily.in/tutorial/python/hello-world/ - Python Syntax, Indentation and Comments → https://codingeasily.in/tutorial/python/python-syntax-comments/ - Variables and Data Types in Python → https://codingeasily.in/tutorial/python/variables-data-types/

urljoin turns relative links such as /tutorial/python/lists/ into full URLs.

Step 4: check robots.txt in code

Python – robots_check.py
from urllib import robotparser

rp = robotparser.RobotFileParser()
rp.set_url("https://codingeasily.in/robots.txt")
rp.read()

for path in ["/tutorial/python/", "/search/", "/config/"]:
    allowed = rp.can_fetch("StudentScraper", "https://codingeasily.in" + path)
    print(f"{path:<20} allowed: {allowed}")
print("crawl delay:", rp.crawl_delay("StudentScraper"), "second(s)")
/tutorial/python/ allowed: True /search/ allowed: False /config/ allowed: False crawl delay: 1 second(s)

Step 5: save a table to CSV (with polite delays)

Python – titles_to_csv.py
import csv, time
import requests
from bs4 import BeautifulSoup

BASE = "https://codingeasily.in"
pages = ["/blog/"]                      # add more pages to this list
rows = []
for path in pages:
    html = requests.get(BASE + path, timeout=10, headers={"User-Agent": "StudentScraper/1.0"}).text
    soup = BeautifulSoup(html, "html.parser")
    for h3 in soup.select("h3[data-en]"):
        rows.append({"title": h3["data-en"], "title_hi": h3["data-hi"]})
    time.sleep(1)                       # be polite: 1 request per second

with open("blog_titles.csv", "w", newline="", encoding="utf-8-sig") as f:
    w = csv.DictWriter(f, fieldnames=["title", "title_hi"])
    w.writeheader()
    w.writerows(rows)

print(len(rows), "titles saved. First two:")
for r in rows[:2]:
    print("-", r["title"], "|", r["title_hi"])
70 titles saved. First two: - What is const in C? Meaning, Syntax and Simple Examples | C में const क्या है? Meaning, Syntax और आसान Examples - Define const in C: 3 Ways to Define Constants (const, #define, enum) | C में Constant Define करने के 3 तरीके (const, #define, enum)

Shortcut: HTML tables with pandas

Python – pandas_read_html.py
import pandas as pd
from io import StringIO

html = open("price_list.html", encoding="utf-8").read()
table = pd.read_html(StringIO(html), attrs={"id": "prices"})[0]
table["Price (₹)"] = table["Price"].str.extract(r"(\d+)").astype(int)
print(table[["Sweet", "Price (₹)", "Stock"]])
Sweet Price (₹) Stock 0 Kaju Katli 900 Yes 1 Ghewar 650 Yes 2 Kalakand 600 No

When scraping will not work

  • JavaScript-rendered pages: the HTML you download is almost empty because data loads later. Look in DevTools → Network for a JSON API, or use a browser tool such as Playwright.
  • Login-only data: do not scrape it unless it is your own account and the terms allow it.
  • Blocking (403/429): slow down, respect robots.txt, or ask the site owner for access.
  • Changing layout: selectors break when the site is redesigned – write code that fails clearly.

Practice tasks

  1. From price_list.html, print only sweets that are in stock with prices as numbers.
  2. Scrape the Python course page and count how many lessons are in each group.
  3. Save the blog titles to JSON instead of CSV.
  4. Write a function that returns None instead of crashing when a selector finds nothing.

Summary

  • Check permission first: terms, robots.txt, and whether an API exists.
  • requests.get (with timeout and User-Agent) downloads; BeautifulSoup parses.
  • Use find/find_all or CSS selectors with select.
  • Clean text with get_text(strip=True), build full links with urljoin, save with csv/json/pandas.
  • Add delays and never collect personal data.

Frequently Asked Questions

Is web scraping legal in India?
Scraping publicly available, non-personal data for learning or analysis is generally accepted, but website terms, copyright and the Digital Personal Data Protection Act 2023 still apply. Do not scrape personal data, copy content to republish it, or bypass logins. When in doubt, ask the site owner.
What is the difference between BeautifulSoup and Selenium/Playwright?
BeautifulSoup only parses HTML you already downloaded; it is fast and light. Selenium and Playwright control a real browser, so they can run JavaScript, click and log in, but they are slower and heavier.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicWorking with APIs and requests Your progress: 27 / 66 (41%) · Lesson 28 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free