Python编程实战 - Python实用工具与库 - 爬取并存储网页数据

在数据分析与自动化任务中,网络爬虫(Web Crawler) 是非常常见的应用场景。 Python 以其丰富的第三方库(如 requestsBeautifulSouplxmlpandas 等)成为实现爬虫的理想语言。 今天我们通过一个完整的案例,学习如何 爬取网页数据保存到本地文件(Excel/CSV)


一、爬虫的基本流程

  1. 发送请求:获取网页内容(HTML)
  2. 解析数据:从 HTML 中提取有用信息
  3. 数据清洗:去除多余字符或空白
  4. 数据存储:保存为 CSV、Excel、数据库等格式

二、使用 requests 获取网页内容

requests 是 Python 最常用的网络请求库,使用起来非常简洁。

python 复制代码
import requests

url = "https://quotes.toscrape.com/"
response = requests.get(url)
print(response.status_code)
print(response.text[:500])  # 只看前500个字符

说明:

  • status_code = 200 表示请求成功。
  • response.text 为网页 HTML 内容。

三、使用 BeautifulSoup 解析网页

BeautifulSoup 是一个非常强大的 HTML 解析工具,可帮助你方便地提取网页结构中的特定内容。

python 复制代码
from bs4 import BeautifulSoup

html = response.text
soup = BeautifulSoup(html, "html.parser")

quotes = soup.find_all("div", class_="quote")

for q in quotes:
    text = q.find("span", class_="text").get_text(strip=True)
    author = q.find("small", class_="author").get_text(strip=True)
    print(f"{author}:{text}")

输出示例:

dart 复制代码
Albert Einstein:"The world as we have created it is a process of our thinking."
J.K. Rowling:"It is our choices that show what we truly are."

四、提取并保存数据

我们可以将提取的数据保存到列表中,再用 pandas 转换成表格格式,最后导出 Excel/CSV 文件。

python 复制代码
import pandas as pd

data = []
for q in quotes:
    text = q.find("span", class_="text").get_text(strip=True)
    author = q.find("small", class_="author").get_text(strip=True)
    data.append({"作者": author, "名言": text})

df = pd.DataFrame(data)
df.to_excel("名言收集.xlsx", index=False)
print("数据已保存到 名言收集.xlsx")

五、爬取多页数据

很多网站内容分页显示,可以通过分析 URL 规律实现多页爬取。

https://quotes.toscrape.com/page/1/ 为例,下一页是 /page/2//page/3/...

python 复制代码
import time
import random

all_data = []

for page in range(1, 6):
    url = f"https://quotes.toscrape.com/page/{page}/"
    print(f"正在爬取第 {page} 页:{url}")
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    quotes = soup.find_all("div", class_="quote")
    
    for q in quotes:
        text = q.find("span", class_="text").get_text(strip=True)
        author = q.find("small", class_="author").get_text(strip=True)
        all_data.append({"作者": author, "名言": text})
    
    time.sleep(random.uniform(1, 2))  # 防止请求过快被封

# 保存数据
df = pd.DataFrame(all_data)
df.to_csv("quotes.csv", index=False, encoding="utf-8-sig")
print("所有页面数据已保存到 quotes.csv")

六、数据清洗与去重

爬取到的数据可能存在重复或空行,可用 Pandas 简单清洗:

python 复制代码
df = pd.read_csv("quotes.csv")
df.drop_duplicates(inplace=True)
df.dropna(subset=["名言"], inplace=True)
df.to_csv("quotes_clean.csv", index=False, encoding="utf-8-sig")
print("清洗完成,保存为 quotes_clean.csv")

七、实战进阶:爬取并存储新闻标题

以某新闻网站为例(如新浪科技频道):

python 复制代码
import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "https://tech.sina.com.cn/"
response = requests.get(url)
response.encoding = "utf-8"
soup = BeautifulSoup(response.text, "html.parser")

titles = [a.get_text(strip=True) for a in soup.find_all("a") if a.get_text(strip=True)]
data = pd.DataFrame({"新闻标题": titles})
data.to_excel("新浪科技新闻.xlsx", index=False)
print("新闻标题已保存到 新浪科技新闻.xlsx")

八、爬虫中的防封与异常处理

为了避免被网站屏蔽,建议:

  1. 设置请求头(User-Agent)

    python 复制代码
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
    requests.get(url, headers=headers)
  2. 控制访问频率 使用 time.sleep() 随机等待 1~3 秒。

  3. 捕获网络异常

    python 复制代码
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
    except requests.RequestException as e:
        print("请求失败:", e)

九、总结

步骤 工具 功能
1 requests 获取网页 HTML
2 BeautifulSoup 解析 HTML 提取数据
3 pandas 存储与清洗数据
4 Excel/CSV 数据落地保存
5 time + random 防止请求过快被封禁

通过以上流程,你已经可以实现一个完整的网页爬取与数据存储脚本,为后续数据分析和可视化打下基础。


相关推荐
网安-轩逸13 分钟前
回归测试原则:确保软件质量的基石
自动化测试·软件测试·python
X***C86222 分钟前
SpringBoot:几种常用的接口日期格式化方法
java·spring boot·后端
Mr_Xuhhh23 分钟前
YAML相关
开发语言·python
i***t91929 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
咖啡の猫37 分钟前
Python中的变量与数据类型
开发语言·python
汤姆yu1 小时前
基于springboot的电子政务服务管理系统
开发语言·python
o***74171 小时前
基于SpringBoot的DeepSeek-demo 深度求索-demo 支持流式输出、历史记录
spring boot·后端·lua
9***J6281 小时前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
S***q1921 小时前
Rust在系统工具中的内存安全给代码上了三道保险锁。但正是这种“编译期的严苛”,换来了运行时的安心。比如这段代码:
开发语言·后端·rust
v***7941 小时前
Spring Boot 热部署
java·spring boot·后端