使用 Python 编写一个简单的网页爬虫

在数据时代,信息是金子。而网络上蕴藏着海量的数据资源,掌握一门自动化获取数据的技术就尤为重要。今天我们将通过 Python 来编写一个简单的网页爬虫,从一个网页中提取我们想要的数据内容。

一、什么是网页爬虫?

网页爬虫(Web Crawler)是一种自动访问网站并抓取其页面内容的程序。它模拟浏览器的行为,访问网站并提取页面中的结构化数据,如文本、图片、链接等。

二、准备工作

我们需要安装以下 Python 库: pip install requests beautifulsoup4

  • requests:用于模拟浏览器请求网页
  • BeautifulSoup:用于解析网页 HTML 结构,提取我们想要的数据。

三、实战:爬取豆瓣电影 Top 250

我们以 豆瓣电影 Top 250 为例,爬取电影标题和评分。

1. 获取网页内容:

python 复制代码
import requests

url = 'https://movie.douban.com/top250'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/114.0.0.0 Safari/537.36'
}

response = requests.get(url, headers=headers)
html = response.text
print(html[:500])  # 预览前500个字符

这里使用了 User-Agent 头信息,模拟浏览器访问,以防被反爬。

2. 解析网页内容

python 复制代码
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
movie_items = soup.find_all('div', class_='item')

for item in movie_items:
    title = item.find('span', class_='title').text
    rating = item.find('span', class_='rating_num').text
    print(f'电影名称:{title},评分:{rating}')

3. 添加分页功能

豆瓣 Top250 分为 10 页,每页 25 部电影,我们需要循环访问每一页:

python 复制代码
def fetch_movies():
    for start in range(0, 250, 25):
        url = f'https://movie.douban.com/top250?start={start}'
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        movie_items = soup.find_all('div', class_='item')

        for item in movie_items:
            title = item.find('span', class_='title').text
            rating = item.find('span', class_='rating_num').text
            print(f'电影名称:{title},评分:{rating}')

fetch_movies()

4.保存数据到 CSV 文件

我们可以将爬取到的数据保存到 .csv 文件中,方便后续分析:

python 复制代码
import csv

with open('douban_top250.csv', 'w', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['电影名称', '评分'])

    for start in range(0, 250, 25):
        url = f'https://movie.douban.com/top250?start={start}'
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        movie_items = soup.find_all('div', class_='item')

        for item in movie_items:
            title = item.find('span', class_='title').text
            rating = item.find('span', class_='rating_num').text
            writer.writerow([title, rating])

四、遇到的问题与解决方案

问题 解决方式
被识别为爬虫封IP 添加 User-Agent,设置请求间隔或使用代理
网页结构变化 使用浏览器开发者工具分析网页结构,更新代码逻辑
中文乱码 注意文件编码使用 utf-8-sig

五、总结

本文主要介绍了如何使用 Python 爬取网页数据,并完成了一个实战项目 ------ 爬取豆瓣 Top250 电影数据,并保存为 CSV 文件。这只是爬虫的起点,更多高级技巧还包括:使用 Selenium 控制浏览器抓取动态页面、使用异步爬虫提升效率(如 aiohttp、scrapy)、使用 IP 代理池绕过反爬,学习爬虫的路程还很漫长。

当然您如果急需获取数据,我也建议您可以试一试一些采集工具:比如浣石采集器、八爪鱼采集器、后羿采集器等都是不错的选择!

相关推荐
causaliy9 小时前
实践六:防盗链知识点——视频
爬虫·音视频
xinxinhenmeihao14 小时前
爬虫导致IP被封号了如何解封?
爬虫·网络协议·tcp/ip
加油20191 天前
音视频处理(三):hls协议和m3u8详解和视频下载爬虫实战
爬虫·音视频·hls·m3u8·mpeg-2·mpeg2-ts·电视迷
闲人编程1 天前
从零开发一个简单的Web爬虫(使用Requests和BeautifulSoup)
前端·爬虫·beautifulsoup·bs4·web·request·codecapsule
B站计算机毕业设计之家1 天前
大数据python招聘数据分析预测系统 招聘数据平台 +爬虫+可视化 +django框架+vue框架 大数据技术✅
大数据·爬虫·python·机器学习·数据挖掘·数据分析
疏狂难除2 天前
spiderdemo第22题与webassembly的跨域
开发语言·javascript·爬虫·rust·wasm·mitmproxy
小白学大数据2 天前
增量爬取策略:如何持续监控贝壳网最新成交数据
爬虫·python·性能优化
苏打水com2 天前
Python 爬虫 3 大核心库深度解析:从原理到实战,覆盖 90% 爬取场景
爬虫
深蓝电商API2 天前
数据清洗标准化:构建可复用的爬虫数据清洗管道(Pipeline)
爬虫·数据清洗
深蓝电商API2 天前
“监狱”风云:如何设计爬虫的自动降级与熔断机制?
爬虫