6Automate the Boring Stuff with Python(第2版)

网页抓取

Web爬虫

requestsBeautifulSoupSelenium数据提取

🎯 AI 时代的学习建议:不要只读理论。理解这一章的设计动机(为什么需要这个概念?)和边界条件(什么情况下会失效?)。当 AI 生成的代码涉及这些概念时,你能判断它是否用对了场景。AI 能帮你总结内容,但无法替代你亲手阅读、思考、建立直觉的过程。

第6章:网页抓取

一、导读

1.1 本章学习目标

第6章讲解 Python 的网页抓取:requests、BeautifulSoup、Selenium。

本章核心学习目标:

  • 掌握 requests:HTTP 请求
  • 理解 BeautifulSoup:HTML 解析
  • 掌握 Selenium:浏览器自动化

1.2 为什么本章如此重要

网页抓取是获取在线数据的强大工具。从数据采集到自动化测试,应用广泛。

1.3 核心问题引导

requests 和 urllib 有什么区别?

BeautifulSoup 如何选择元素?

什么时候需要 Selenium?


二、核心概念详解

2.1 requests

python
import requests

# GET 请求
response = requests.get('https://httpbin.org/get')
print(response.status_code)  # 200
print(response.json())

# 带参数
params = {'q': 'python', 'page': 1}
response = requests.get('https://httpbin.org/get', params=params)

# POST 请求
data = {'name': 'Alice', 'age': 30}
response = requests.post('https://httpbin.org/post', json=data)

# 带 headers
headers = {'User-Agent': 'MyApp/1.0'}
response = requests.get('https://httpbin.org/get', headers=headers)

# Session (保持 cookies)
session = requests.Session()
session.get('https://example.com/login', data={'user': 'admin', 'pass': '123'})
response = session.get('https://example.com/dashboard')

2.2 BeautifulSoup

python
from bs4 import BeautifulSoup
import requests

html = requests.get('https://example.com').text
soup = BeautifulSoup(html, 'html.parser')

# 选择元素
title = soup.find('h1').text
links = soup.find_all('a')
for link in links:
    print(link.get('href'), link.text)

# CSS 选择器
items = soup.select('.product-item')
for item in items:
    name = item.select_one('.name').text
    price = item.select_one('.price').text
    print(f"{name}: {price}")

# 提取属性
img = soup.find('img')
src = img.get('src')
alt = img.get('alt', 'No description')

2.3 Selenium

python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://example.com')

# 等待元素
wait = WebDriverWait(driver, 10)
search_box = wait.until(EC.presence_of_element_located((By.NAME, 'q')))

# 输入和点击
search_box.send_keys('python')
search_box.submit()

# 等待结果
results = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.result')))
for result in results:
    print(result.text)

driver.quit()

三、实战案例

3.1 案例一:抓取商品价格

python
import requests
from bs4 import BeautifulSoup

def scrape_prices(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    products = []
    for item in soup.select('.product'):
        name = item.select_one('.name').text.strip()
        price_text = item.select_one('.price').text.strip()
        price = float(price_text.replace('$', '').replace(',', ''))
        products.append({'name': name, 'price': price})
    
    return sorted(products, key=lambda p: p['price'])

# 使用
products = scrape_prices('https://example-shop.com/products')
for p in products[:5]:
    print(f"{p['name']}: ${p['price']:.2f}")

四、本章小结

requests 简洁的 HTTP 客户端

BeautifulSoup 解析 HTML

Selenium 自动化浏览器操作


五、思考与练习

如何处理反爬虫机制?

如何抓取 JavaScript 渲染的页面?


6/7网页抓取
0%