打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python爬取豆瓣影评存数据库【新手必入】

效果展示

需要用到的库

import requestsfrom time import sleepfrom lxml import etreeimport pymysql

首先看看我们要爬的页面链接

https://movie.douban.com/subject/30313969/comments?start=0&limit=20&status=P&sort=new_score

 这个链接只是第一页,我们要爬取所有的数据,就必须翻页一页一页的爬

我们先看看第二页的网页链接

https://movie.douban.com/subject/30313969/comments?start=20&limit=20&status=P&sort=new_score

我们发现 ?start= 这个地方出现了变化,从0 变成了 20 其他都没变, start中文意思是开始,简单分析可得,一页有二十个评论,所以后面的按照 ?start=40,?start=60 依次递增

可以写个for循环实现,也不爬取太多,前200个评论即可 

for i in range(0,220,20):    #转为字符串类型    i = str(i)    #将i代入    url = 'https://movie.douban.com/subject/30313969/comments?start=' i '&limit=20&status=P&sort=new_score'

添加UA伪装请求头 

# UA伪装请求头header = {    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chromeh/81.0.4044.138 Safari/537.36'}

按F12查看网页源代码,并分析数据

使用xpath进行数据爬取

for i in range(0,220,20):    #转为字符串类型    i = str(i)    #将i代入    url = 'https://movie.douban.com/subject/30313969/comments?start=' i '&limit=20&status=P&sort=new_score'    response = requests.get(url=url,headers=header).text    tree = etree.HTML(response)    ul = tree.xpath('//div[@class="comment"]')    #遍历二十个存储评论信息的div    for li in ul:        #网名        name = li.xpath('.//span[@class="comment-info"]/a/text()')[0]        #评价        rating = li.xpath('.//span[@class="comment-info"]/span[2]/@title')[0]        # 评论时间  # 评论时间  这里会有换行和许多空格        timed = li.xpath('.//span[@class="comment-info"]/span[3]/text()')[0]        #去掉空格        times = timed.replace(" ",'')        #去掉换行        time = times.replace("\n", "")        #评论        comment = li.xpath('.//span[@class="short"]/text()')[0]                print('网名:',name,'  评价:',rating,'  时间:',time,'  评论:',comment)

接下来开始存入数据库

在数据库里创建一个叫douban的库,再创建一个叫data的表用于存放数据

存入数据库

#连接数据库conn = pymysql.connect(host='localhost', port=3306, user='数据库用户名', passwd='数据库密码', database='douban',charset='utf8')# 生成游标对象cur = conn.cursor()#使用添加语句sql1 = "INSERT INTO data VALUES (%s,%s,%s,%s)"#这里写上sql1的四个%s对应的值da = [name,rating,time,comment] #[网名,评价,时间,评论]try:    cur.execute(sql1, da)  # 执行插入的sql语句    conn.commit()  # 提交到数据库执行except Exception:    # 发生错误时回滚    conn.rollback()    print("出现错误/可能与重复的值有关")conn.close()  # 关闭数据库连接

完整代码

import requestsfrom time import sleepfrom lxml import etreeimport pymysql# UA伪装请求头header = {    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chromeh/81.0.4044.138 Safari/537.36'}for i in range(0,200,20):    #转为字符串类型    i = str(i)    #将i代入    url = 'https://movie.douban.com/subject/30313969/comments?start=' i '&limit=20&status=P&sort=new_score'    response = requests.get(url=url,headers=header).text    tree = etree.HTML(response)    ul = tree.xpath('//div[@class="comment"]')    #遍历二十个存储评论信息的div    for li in ul:        #网名        name = li.xpath('.//span[@class="comment-info"]/a/text()')[0]        #评价        rating = li.xpath('.//span[@class="comment-info"]/span[2]/@title')[0]        # 评论时间  # 评论时间  这里会有换行和许多空格        timed = li.xpath('.//span[@class="comment-info"]/span[3]/text()')[0]        #去掉空格        times = timed.replace(" ",'')        #去掉换行        time = times.replace("\n", "")        #评论        comment = li.xpath('.//span[@class="short"]/text()')[0]        #连接数据库        conn = pymysql.connect(host='localhost', port=3306, user='数据库用户名', passwd='数据库密码', database='douban',charset='utf8')        # 生成游标对象        cur = conn.cursor()        #使用添加语句        sql1 = "INSERT INTO data VALUES (%s,%s,%s,%s)"        #这里写上sql1的四个%s对应的值        da = [name,rating,time,comment] #[网名,评价,时间,评论]        try:            cur.execute(sql1, da)  # 执行插入的sql语句            conn.commit()  # 提交到数据库执行        except Exception:            # 发生错误时回滚            conn.rollback()            print("出现错误/可能与重复的值有关")        conn.close()  # 关闭数据库连接    #做一个进度条显示进度    i = int(i)    print("已将%s条评论存入数据库中"%i)
来源:https://www.icode9.com/content-2-854551.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python在数据库的基本操作(修改数据)
使用 Python 爬取简书网的所有文章
第一周:JDBC中批量插入数据问题
Winform  用C#创建SQL数据库
C# 怎么执行SQL语句
Python爬虫:现学现用xpath爬取豆瓣音乐
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服