当前位置 博文首页 > 小航冲冲冲的博客:python爬取豆瓣影评存数据库【新手必入】

    小航冲冲冲的博客:python爬取豆瓣影评存数据库【新手必入】

    作者:[db:作者] 时间:2021-06-15 15:12

    效果展示

    需要用到的库

    import requests
    from time import sleep
    from lxml import etree
    import 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 requests
    from time import sleep
    from lxml import etree
    import 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)

    ?