Python获取时光网电影数据的实例代码

  # Encoding: utf-8

  # Author: furongbing

  # Date: 2021-11-19 20:54

  # Project name: FrbPythonFiles

  # IDE: PyCharm

  # File name: Mtime

  import requests

  import pandas as pd

  from threading import Thread

  import time

  import json

  # 模块说明:

  """

  从时光网上按年代获取指定年份电影的数据

  """

  # 更新日志:

  """

  1、2021-11-19:

  a、完成初版

  """

  # 待修改:

  """

  """

  # 请求头数据

  headers = {"Accept": "application/json, text/plain, */*",

  "Accept-Encoding": "gzip, deflate",

  'Accept-Language': 'zh-CN,zh;q=0.9',

  'Connection': 'keep-alive',

  'Content-Type': 'application/x-www-form-urlencoded',

  'Cookie': '_tt_=FB8A3FAD4704D42543B7EC121C2565AA; __utma=196937584.1082595229.1637326918.1637326918.1637326918.1; __utmz=196937584.1637326918.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); Hm_lvt_07aa95427da600fc217b1133c1e84e5b=1637241042,1637326637,1637374129; Hm_lpvt_07aa95427da600fc217b1133c1e84e5b=1637374170',

  'Host': 'front-gateway.mtime.com',

  'Origin': 'http://film.mtime.com',

  'Referer': 'http://film.mtime.com/',

  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'

  }

  pagesize = 20 # todo 获取的每页数据条数,一般建议成默认的20就可以了,设置的太大,每页包含的数据量就大,某一条电影数据出错会导致其它数据也被抛弃。

  data = []

  error = []

  def get_data(p_year=1987): # 按照年份获取当年度所有的电影数据

  url = 'http://front-gateway.mtime.com/mtime-search/search/unionSearch2' # 请求的url

  params = {'year': p_year, 'pageSize': pagesize, 'pageIndex': 1, 'searchType': 0} # 请求的表单数据

  # 获取当年度所有的电影的数量,继而计算要获取多少页

  try:

  r = requests.get(url=url, params=params, headers=headers, timeout=10)

  r.encoding = r.apparent_encoding

  all_data = json.loads(r.text)

  moviesCount = all_data['data']['moviesCount']

  pages = round(moviesCount / pagesize)

  except Exception:

  moviesCount = 1000

  pages = round(moviesCount / pagesize)

  # 定义变量

  来源 = '时光网'

  年代 = p_year

  ID, 中文名, 英文名, 类型, 形式, 海报url, 评分, 导演, 主演, 详情, 可播放, 国家地区, 上映日期, 片长, 票房, 观看日期 = [''] * 16

  for page in range(pages): # todo 一共要获取多少页

  if page % 10 == 0: # 每10页输出一次进度

  print(f'已完成 {100 * page / pages:.2f}%')

  pageindex = page + 1

  params = {'year': p_year, 'pageSize': pagesize, 'pageIndex': pageindex, 'searchType': 0} # 请求的表单数据

  try: # 获取指定页的电影数据

  r = requests.get(url=url, params=params, headers=headers, timeout=10)

  r.encoding = r.apparent_encoding

  all_data = json.loads(r.text)

  movies = all_data['data']['movies']

  # 获取电影具体信息

  for movie in movies:

  ID = movie['movieId']

  中文名 = movie['name']

  英文名 = movie['nameEn']

  类型 = movie['movieType']

  形式 = movie['movieContentType']

  海报url = movie['img']

  其它译名 = movie['titleOthersCn']

  评分 = movie['rating']

  导演 = movie['directors']

  主演 = movie['actors']

  详情 = movie['href']

  可播放 = movie['canPlay']

  国家地区 = movie['locationName']

  上映日期 = movie['realTime']

  片长 = movie['length']

  info = [来源, 年代, ID, 中文名, 英文名, 类型, 形式, 海报url, 其它译名, 评分, 导演, 主演, 详情, 可播放, 国家地区, 上映日期, 片长, 票房, 观看日期]

  data.append(info)

  except Exception as err:

  er_year, er_pagesize, er_pageindex, er_msg = p_year, pagesize, pageindex, err

  error.append([er_year, er_pagesize, er_pageindex, er_msg])

  print(f"出错啦,出错年份:{p_year},pagesize:{pagesize},page:{pageindex},出错原因:{er_msg}")

  continue

  if __name__ == '__main__':

  begin = time.perf_counter()

  threads = []

  for year in range(2020, 2021): # todo 此处可以自定义要获取的年份

  t = Thread(target=get_data, args=(year,))

  threads.append(t)

  t.start()

  for t in threads:

  t.join()

  with open('error.txt', 'w', encoding='utf-8') as f:

  f.write(str(error))

  data.insert(0, ['来源', '年代', 'ID', '中文名', '英文名', '类型', '形式', '海报url', '其它译名', '评分', '导演', '主演', '详情', '可播放', '国家地区', '上映日期', '片长', '票房', '观看日期'])

  df = pd.DataFrame(data)

  df.to_excel(excel_writer=r'film.xlsx', sheet_name='sheet1', index=None, header=False) # todo film.xlsx为最后保存的文件名

  end = time.perf_counter()

  runtime = end - begin

  print(f'运行时长:{runtime:.3f}秒。')