Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟡 Advanced Python  ·  Lesson 27

Web Scraping Basics

Web scraping क्या है?

Web scraping का मतलब है program web page download करके ज़रूरी जानकारी निकाले – prices, titles, tables, links – हाथ से copy करने की जगह। इसके लिए Python सबसे लोकप्रिय है क्योंकि दो libraries हैं: requests (page download) और BeautifulSoup (HTML के अंदर चीज़ें ढूँढना)।

StepTool
1. जाँचें कि अनुमति है (terms, robots.txt, API उपलब्ध?)Browser, urllib.robotparser
2. HTML download करेंrequests.get()
3. Parse करके elements ढूँढेंBeautifulSoup, CSS selectors
4. साफ़ करके save करेंcsv, json, pandas
5. शिष्ट रहेंRequests के बीच delay, अपनी पहचान दें
Terminal
pip install requests beautifulsoup4
⚖️ पहले कानूनी और नैतिक नियम

सिर्फ़ public data scrape करें, website की terms और robots.txt मानें, बिना अनुमति personal data (phone numbers, emails) इकट्ठा न करें, login या CAPTCHA bypass न करें, और delay रखें ताकि server पर बोझ न पड़े। Site API देती हो तो API इस्तेमाल करें।

Step 1: BeautifulSoup से HTML parse करें

पहले एक छोटी HTML file पर अभ्यास करें। इसे price_list.html नाम से save करें:

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: select() के साथ CSS selectors

अगर आप CSS जानते हैं तो select() और select_one() elements ढूँढने का सबसे तेज़ तरीका हैं। Chrome में element पर right-click → Inspect से उसके tags और 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
Selectorक्या ढूँढता है
h2सभी h2 tags
.priceclass="price"
#pricesid="prices"
table tr.itemtable के अंदर item class वाली tr
a[href]href वाले links
td:first-childहर row की पहली cell

Step 3: असली page scrape करें

अब असली page download करें – इसी Python course की lesson list – और हर lesson link निकालें। (सीखने के लिए CodingEasily scrape करने की अनुमति है।)

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 /tutorial/python/lists/ जैसे relative links को पूरे URLs में बदलता है।

Step 4: code में robots.txt जाँचें

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: table को CSV में save करें (शिष्ट 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: pandas से HTML tables

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

कब scraping काम नहीं करेगी

  • JavaScript से बनने वाले pages: download किया HTML लगभग ख़ाली होता है क्योंकि data बाद में आता है। DevTools → Network में JSON API ढूँढें, या Playwright जैसा browser tool लें।
  • सिर्फ़ login वाला data: तब तक scrape न करें जब तक आपका अपना account न हो और terms अनुमति न दें।
  • Blocking (403/429): धीमे चलें, robots.txt मानें, या site owner से access माँगें।
  • बदलता layout: site redesign होने पर selectors टूटते हैं – ऐसा code लिखें जो साफ़ error दे।

अभ्यास

  1. price_list.html से सिर्फ़ stock वाली मिठाइयाँ numbers वाली prices के साथ छापें।
  2. Python course page scrape करके हर group में lessons गिनें।
  3. Blog titles को CSV की जगह JSON में save करें।
  4. ऐसा function लिखें जो selector को कुछ न मिलने पर crash न होकर None लौटाए।

सारांश

  • पहले अनुमति जाँचें: terms, robots.txt, और API है या नहीं।
  • requests.get (timeout और User-Agent के साथ) download करता है; BeautifulSoup parse करता है।
  • find/find_all या select के साथ CSS selectors इस्तेमाल करें।
  • get_text(strip=True) से text साफ़ करें, urljoin से पूरे links बनाएँ, csv/json/pandas से save करें।
  • Delays रखें और personal data कभी इकट्ठा न करें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या भारत में web scraping कानूनी है?
सीखने या analysis के लिए public, non-personal data scrape करना आम तौर पर स्वीकार्य है, पर website की terms, copyright और Digital Personal Data Protection Act 2023 लागू रहते हैं। Personal data scrape न करें, content दोबारा publish करने के लिए copy न करें, और login bypass न करें। शक हो तो site owner से पूछें।
BeautifulSoup और Selenium/Playwright में क्या अंतर है?
BeautifulSoup सिर्फ़ download किया हुआ HTML parse करता है; यह तेज़ और हल्का है। Selenium और Playwright असली browser चलाते हैं, इसलिए JavaScript चला सकते हैं, click और login कर सकते हैं, पर धीमे और भारी हैं।
← Back to Python Tutorial
🔗

Share this topic with a friend

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

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

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

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicAPIs और requests के साथ काम आपकी प्रगति: 27 / 66 (41%) · Lesson 28 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें