Python 爬虫

Fetching pages politely, parsing HTML, and handling pagination and rate limits.

Intermediate
Key PointsParse with an HTML parser, not regex; sleep between requests and identify yourself with a real User-Agent.

Fetch and Parse

Fetch HTML with requests, extract with BeautifulSoup CSS selectors. Prefer the lxml parser — much faster than the built-in one.

Bash
pip install requests beautifulsoup4 lxml
Python
import requests
from bs4 import BeautifulSoup

headers = {"User-Agent": "Mozilla/5.0 (compatible; MyBot/1.0)"}
resp = requests.get("https://example.com/books", headers=headers, timeout=10)
resp.raise_for_status()

soup = BeautifulSoup(resp.text, "lxml")
for item in soup.select("article.book")[:3]:
    title = item.select_one("h3").get_text(strip=True)
    price = item.select_one(".price").get_text(strip=True)
    print(title, price)
Output
Python 编程 39.90
Go 语言实战 45.00
Rust 程序设计 49.00

Pagination

Pagination is either a URL param or a next button. The URL param is more robust — just loop until empty.

Python
import time

rows = []
for page in range(1, 4):
    r = requests.get(f"https://example.com/books?page={page}", headers=headers, timeout=10)
    soup = BeautifulSoup(r.text, "lxml")
    items = soup.select("article.book")
    if not items:
        break
    rows += [i.select_one("h3").get_text(strip=True) for i in items]
    time.sleep(1)          # 限速:每秒最多 1 个请求

print(len(rows))
Output
36

Anti-Scraping Reality

ObstacleTypical handling
Dynamic JS renderingUse Playwright/Selenium, or find the JSON API
Rate limitingSleep + rotate IP + respect Retry-After
Login wallUse a session with cookies, never store others' credentials
CaptchaStop — usually means you are not welcome
Look for the JSON API first: many "dynamic pages" are just an XHR returning JSON — far more stable than DOM parsing.

Friends & Partners