Web Scraping Basics
Web scraping क्या है?
Web scraping का मतलब है program web page download करके ज़रूरी जानकारी निकाले – prices, titles, tables, links – हाथ से copy करने की जगह। इसके लिए Python सबसे लोकप्रिय है क्योंकि दो libraries हैं: requests (page download) और BeautifulSoup (HTML के अंदर चीज़ें ढूँढना)।
| Step | Tool |
|---|---|
| 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, अपनी पहचान दें |
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><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>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}")Step 2: select() के साथ CSS selectors
अगर आप CSS जानते हैं तो select() और select_one() elements ढूँढने का सबसे तेज़ तरीका हैं। Chrome में element पर right-click → Inspect से उसके tags और classes देखें।
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"])| Selector | क्या ढूँढता है |
|---|---|
h2 | सभी h2 tags |
.price | class="price" |
#prices | id="prices" |
table tr.item | table के अंदर 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 करने की अनुमति है।)
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"]))urljoin /tutorial/python/lists/ जैसे relative links को पूरे URLs में बदलता है।
Step 4: code में robots.txt जाँचें
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)")Step 5: table को CSV में save करें (शिष्ट delays के साथ)
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"])Shortcut: pandas से HTML tables
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"]])कब 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 दे।
अभ्यास
price_list.htmlसे सिर्फ़ stock वाली मिठाइयाँ numbers वाली prices के साथ छापें।- Python course page scrape करके हर group में lessons गिनें।
- Blog titles को CSV की जगह JSON में save करें।
- ऐसा function लिखें जो selector को कुछ न मिलने पर crash न होकर
Noneलौटाए।
सारांश
- पहले अनुमति जाँचें: terms, robots.txt, और API है या नहीं।
requests.get(timeout और User-Agent के साथ) download करता है;BeautifulSoupparse करता है।find/find_allयाselectके साथ CSS selectors इस्तेमाल करें।get_text(strip=True)से text साफ़ करें,urljoinसे पूरे links बनाएँ, csv/json/pandas से save करें।- Delays रखें और personal data कभी इकट्ठा न करें।
