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 防止请求过快被封禁

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


相关推荐
Ryan ZX2 小时前
【Go语言基础】序列化和反序列化
开发语言·后端·golang
回家路上绕了弯2 小时前
跨境数据延迟高?5 大技术方向 + 实战案例帮你解决
分布式·后端
SimonKing2 小时前
为什么0.1 + 0.2不等于0.3?一次讲透计算机的数学“Bug”
java·数据库·后端
绝无仅有2 小时前
某团互联网大厂的网络协议与数据传输
后端·面试·架构
陈辛chenxin2 小时前
【大数据技术01】数据科学的基础理论
大数据·人工智能·python·深度学习·机器学习·数据挖掘·数据分析
绝无仅有2 小时前
某多多面试相关操作系统、分布式事务、消息队列及 Linux 内存回收策略
后端·面试·架构
蒋星熠3 小时前
爬虫中Cookies模拟浏览器登录技术详解
开发语言·爬虫·python·正则表达式·自动化·php·web
IT_陈寒3 小时前
JavaScript 性能优化实战:我通过这7个技巧将页面加载速度提升了65%
前端·人工智能·后端
JaguarJack3 小时前
用 LaraDumps 高效调试 PHP 和 Laravel
后端·php