(2-2)python+selenium第二个自动化脚本:用函数实现获取猫眼电影中排名前100的

用函数实现:从猫眼电影的排行中,选出排名在前十页的电影信息,包括:
 排名:1
URL://ms0.meituan.net/mywww/image/loading_2.e3d934bf.png
片名:霸王别姬
                主演:张国荣,张丰毅,巩俐
        上映时间:1993-01-01(中国香港)
得分:9.6

      '''

import json
import requests
from requests.exceptions import RequestException
import re,time
#获取网页源代码
def get_one_page(url):
      try:
            response=requests.get(url)
            if response.status_code==200:
                  return response.text
            return None
      except RequestException:
            return None
#利用正则表达式得到数据,以字典形式表示出来
def parse_one_page(html):
      pattern = re.compile('<dd>.*?board-index.*?>(.*?)</i>.*?src="(.*?)".*?<p class="name"><a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',re.S)
      items = re.findall(pattern,html)
      for item in items:
            yield{        #yield字典,必须放在函数里使用
                  'index':item[0],
                  'image': item[1],
                  'title': item[2],
                  'actor': item[3].strip()[3:],
                  'time': item[4].strip()[5:],

                  'score': item[5] + item[6]
                  }
#写入文件
def write_to_file(content):
      with open('maoyandy+def.txt','a',encoding='utf-8')as f:
            f.write(json.dumps(content,ensure_ascii=False)+'\n')
#
def main(offset):
      url='http://maoyan.com/board/4?offset='+str(offset)
      html=get_one_page(url)
      for item in parse_one_page(html):
            print(item)
            write_to_file(item)
if __name__=='__main__':
      for i in range(10):
            main(offset=i*10)
            time.sleep(1)






















猜你喜欢

转载自blog.csdn.net/qq_34173491/article/details/80765160