BeautifulSoup爬虫

一、需求分析

电影评价对于一部电影的好坏至关重要,为了获取电影评价数据,本实验选择针对豆瓣上的电影《我和我的祖国》使用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)

三、运行结果

 四、源代码||||||||||||||||||||||||||||||||(私信)

............

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力代码不掉头发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值