一、需求分析
电影评价对于一部电影的好坏至关重要,为了获取电影评价数据,本实验选择针对豆瓣上的电影《我和我的祖国》使用BeautifulSoup库进行评价数据爬取。
电影评价地址为:https://movie.douban.com/subject/32659890/comments
二、实验步骤
1.安装BeautifulSoup和lxml。
2.网址网页结构分析。
打开电脑上Chrome浏览器或者firefox浏览器访问目标网址,随后打开浏览器开发者工具对网页结构进行分析。可以看到有大量的评论数据,所以该评论数据做了分页处理。
随后点击下一页,可以得到新的网址:
https://movie.douban.com/subject/32659890/comments?start=20&limit=20&status=P&sort=new_score
可以发现start个limit的作用,每页有20条评论,start参数以20递增,其他参数不变。
3.解析网页内容。
本实验需要获取的信息有:评论者姓名、评论时间、评论内容。随后在打开的电影评论中用开发者工具定位到三个目标信息地方。
4.利用BeautifulSoup解析网页内容。
(1)建立get_html为Requests中GET方法的通用函数,用于获取页面的HTML信息。
from bs4 import BeautifulSoup
import requests
def get_html(url,time=10):
head={'User-Agent':'Mozilla/5.0 (Windows NT 10.0:WOW64) AppleWebkit/537.36 (KHiML, like Gecko) Chrome/75.0.3770.100 Safari/537.36')
try:
r=requests.get(url,headers=head,timeout=time)
prin(r.encoding)
r.raise_for_status()
return r.text
except Exception as error:
print(error)
(2)建立parse函数主要利用BeatifulSoup中select解析、提取评论者姓名,评论时间,评论内容目标内容。
def parse(html):
soup=BeautifulSoup(html,'html')
commentsList = soup.select("#comments > div.comment-item")
pageComments = []
for commentTag in commentsList:
comment_dict={}
comment_dict["name"]=commentTag.select('div.comment > h3 > span.comment-info > a')[0].text
comment_dict["time"]=commentTag.select('div.comment > h3 > span.comment-info > span.comment-time')[0].text
comment_dict["comment"]=commentTag.select('div.comment > p > span')[0].text
pageComments.append(comment_dict)
return pageComments
(3)建立main函数,负责整合流程,提前准备网址翻页的url用户请求并解析、控制数据输入输出。
if _name_ == "_main_":
url_first="https://movie.douban.com/subject/32659890/comments"
num=int(input("请输入要获取的页数!"))
comment==[]
for i in range(num):
urlNum=str(i*20)
url=url_first='?start='+urlNum+'&limit=20&sort=new_score&status=p&percent_type='
print("url:",url)
html=get_html(url)
pageComments=parse(html)
comments += pageComments
print("获取第%d:"%i)
for item in comments:
print(item)
三、运行结果
四、源代码||||||||||||||||||||||||||||||||(私信)
............