1. 程式人生 > >(2-2)python+selenium第二個自動化指令碼:用函式實現獲取貓眼電影中排名前100的

(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)