欢迎光临散文网 会员登陆 & 注册

python爬取豆瓣影评用户时间评价内容

2023-06-16 12:34 作者:duokkshu  | 我要投稿


import requests
from bs4 import BeautifulSoup
import time
import random

# 如果想多爬几页可以将16修改为更大的偶数
for i in range(2, 16, 2):
   url = 'https://movie.douban.com/subject/34841067/comments?start={}0&limit=20&status=P&sort=new_score'.format(i)
   headers = {
       'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15'
   }

   # 请求
   r=requests.get(url, headers=headers)

   if r.status_code == 200:
       # 获取标题
       html = BeautifulSoup(r.text, "html.parser")
       title = html.find("h1").text

       # 获取用户名、评论、评分、时间
       divs = html.find_all("div", class_="comment")

       s = {"力荐": "★★★★★", "推荐": "★★★★", "还行": "★★★", "较差": "★★", "很差": "★"}

       with open(f"{title}.txt", "a+", encoding="utf-8") as f:
           for div in divs:
               print("---------------------------------")
               name = div.find("a", class_="").text
               print("用户名:", name)

               content = div.find("span", class_="short").text
               print("用户评论:", content)

               score = None
               for i in range(1, 6):
                   try:
                       score = s[div.find(f"span", class_=f"allstar{i}0 rating")["title"]]
                   except:
                       continue

               if score is None:
                   score = "用户未评分"

               time_str = div.find('span', class_='comment-time')['title']
               time_tuple = time.strptime(time_str, '%Y-%m-%d %H:%M:%S')
               time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_tuple)

               print("评分:", score)
               print("时间: ", time_formatted)
               print(f"[+]...{name} 的评论已爬取")
               f.write("\n")
               f.write(str([name, score, content, time_formatted]))

           f.close()

   random_sleep_time = random.randint(1, 3)
   time.sleep(random_sleep_time)

python爬取豆瓣影评用户时间评价内容的评论 (共 条)

分享到微博请遵守国家法律