当前位置:   article > 正文

利用Python爬取豆瓣影评_python影评

python影评

利用Python爬取豆瓣影评

一、查找短评存放的标签

在这里插入图片描述

二、爬取影片短评具体代码

# _*_ coding:UTF-8 _*_
import os
import requests
import time
from bs4 import BeautifulSoup
import sys
import  re                           ##正则表达式
import urllib.request
import io

os.chdir(r'D:\python')

################################################################爬取《寄生虫》电影短评
def get_urls(urls , num):
    req = urllib.request.urlopen(urls)
    html = BeautifulSoup(req , features='html.parser')              ##若前面为requests.get()函数则需要改为req.text

    for i in range(0,20):
        #print(i + num*20)
        Review = html.find_all('span', class_='short')[i].text
        Review = (str(bytes(Review, encoding='utf-8').decode('utf-8').encode('gbk', 'ignore').decode('gbk')))
        ##str不具有decode属性,必须先将其转换为bytes,转化为bytes要制定其编码,然后将其utf8解码然后再编码成gbk,
        # 同时备注‘ignore’属性,忽视无法编码的emoji,最后解码然后转换成str,便可输出到txt
        print(Review)


#将输出重定向到txt文件
output=sys.stdout                                       ## 创建定向输出程序
outputfile=open("寄生虫短评.txt",'w',encoding='utf-8')       ## 创建文件夹
sys.stdout=outputfile                                   ## 定向输出txt文件

k=0
while k <= 10:
    urls = 'https://movie.douban.com/subject/27010768/comments?start=' + str(k*20) + '&limit=20&sort=new_score&status=P'
    get_urls(urls , k)
    time.sleep(2)
    k += 1

outputfile.close()
sys.stdout=output


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/686988
推荐阅读
相关标签
  

闽ICP备14008679号