Python之爬蟲-貓眼電影

Python之爬蟲-貓眼電影

#!/usr/bin/env python
# coding: utf-8

import json
import requests
import re
import time
# 貓眼多了反爬蟲,速度過快,則會無響應,因此這裏多了一個延時等待
from requests.exceptions import RequestException


def get_one_page(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36(KHTML, like Gecko) '
                          'Chrome/52.0.2743.116 Safari/537.36',
        }
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text  # 使得get_one_page()函數輸出是一個文本
        return None
    except RequestException:
        return None


def parse_one_page(html):
    pattern = re.compile(
        '<dd>.*?board-index.*?>(.*?)</i>.*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?'
        'integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',
        re.S)  # 正則表達式獲取須要保存的東西編譯成正則表達式對象
    items = re.findall(pattern, html)  # 遍歷html文件中的全部pattern正則表達式對象
    for item in items:  # 把提取的對象裝入字典中
        yield {
            'index': item[0],
            'title': item[1],
            'actor': item[2].strip()[3:],
            'time': item[3].strip()[5:],
            'score': item[4] + item[5]
        }


def write_to_file(content):  # 把文件寫入並保存在result.tx + '\n')
    with open('result.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')


def main(offset):  # 遍歷TOP100的電影的全部網址
    url = 'http://maoyan.com/board/4?offset=' + str(offset)  # 接收一個偏移量offset
    html = get_one_page(url)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)


if __name__ == '__main__':  # 建立一個偏移量offset
    for i in range(10):
        main(offset=i * 10)
        time.sleep(1)
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息