准备工作

pip install requests beautifulsoup4 lxml

获取页面

import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
resp = requests.get('https://example.com', headers=headers, timeout=10)
resp.encoding = resp.apparent_encoding   # 自动识别编码
html = resp.text

用 BeautifulSoup 解析

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'lxml')

# 选择器
titles = soup.select('h2.title')          # CSS 选择器
for t in titles:
    print(t.get_text(strip=True))

# 找链接
for a in soup.select('a[href]'):
    href = a['href']
    if href.startswith('/'):
        href = 'https://example.com' + href

翻页采集

for page in range(1, 6):
    url = f'https://example.com/list?page={page}'
    resp = requests.get(url, headers=headers, timeout=10)
    soup = BeautifulSoup(resp.text, 'lxml')
    # 解析本页数据...
    time.sleep(1)   # 礼貌限速,别打爆别人服务器

处理反爬

合规提醒:只爬允许的数据,遵守 robots.txt,别给目标服务器造成压力,商业化使用需确认版权。