Python 爬虫入门:抓取豆瓣电影 Top250 数据
爬虫概述
网络爬虫(Web Crawler),又称网页蜘蛛或网络机器人,是一种按照一定规则自动抓取互联网信息的程序。它模拟浏览器发送网络请求,接收响应并解析数据。
原则上,只要是浏览器能做的事情,爬虫理论上都能做。在大数据时代,信息获取自由了,但同时也伴随着海量无效垃圾信息。如何从碎片化信息中筛选出有价值的内容?答案是利用技术手段进行自动化收集与分析。
准备工作
虽然多种语言(如 PHP, Java, C#, C++)都可以编写爬虫,但 Python 因其语法简洁、库丰富而成为首选。
- 环境搭建:安装 Python 3.x 版本(推荐 3.8+)。
- 开发工具:推荐使用 PyCharm 或 VS Code。
- 依赖库:
urllib:标准库,用于发送 HTTP 请求。BeautifulSoup4:用于 HTML/XML 解析。re:标准库,用于正则表达式匹配。xlwt:用于将数据写入 Excel 文件。sqlite3:可选,用于数据库存储。
项目实战:爬取豆瓣电影 Top250
本案例以爬取豆瓣电影 Top250 榜单为例,目标是将电影详情链接、图片、名称、评分等信息保存至本地。
核心流程
- 爬取网页:构造 URL 列表,循环请求页面源码。
- 解析数据:使用 BeautifulSoup 和正则表达式提取关键信息。
- 保存数据:将清洗后的数据存储为 Excel 文件或数据库。
代码实现
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re
import urllib.request, urllib.error
import xlwt
# 定义正则表达式模式
findLink = re.compile(r'<a href="(.*?)">')
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人评价</span>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
findBd = re.(, re.S)
():
baseurl =
datalist = getData(baseurl)
savepath =
saveData(datalist, savepath)
():
datalist = []
i (, ):
url = baseurl + (i * )
html = askURL(url)
soup = BeautifulSoup(html, )
item soup.find_all(, class_=):
data = []
item_str = (item)
link = re.findall(findLink, item_str)[]
data.append(link)
imgSrc = re.findall(findImgSrc, item_str)[]
data.append(imgSrc)
titles = re.findall(findTitle, item_str)
(titles) == :
ctitle = titles[]
otitle = titles[].replace(, )
data.append(ctitle)
data.append(otitle)
:
data.append(titles[])
data.append()
rating = re.findall(findRating, item_str)[]
data.append(rating)
judgeNum = re.findall(findJudge, item_str)[]
data.append(judgeNum)
inq = re.findall(findInq, item_str)
(inq) != :
inq = inq[].replace(, )
data.append(inq)
:
data.append()
bd = re.findall(findBd, item_str)[]
bd = re.sub(, , bd)
bd = re.sub(, , bd)
data.append(bd.strip())
datalist.append(data)
datalist
():
head = {
:
}
request = urllib.request.Request(url, headers=head)
html =
:
response = urllib.request.urlopen(request)
html = response.read().decode()
urllib.error.URLError e:
(e, ):
()
(e, ):
()
html
():
book = xlwt.Workbook(encoding=, style_compression=)
sheet = book.add_sheet(, cell_overwrite_ok=)
col = (, , , , , , , )
i (, ):
sheet.write(, i, col[i])
i (, ):
data = datalist[i]
j (, ):
sheet.write(i + , j, data[j])
book.save(savepath)
__name__ == :
main()


