正则爬取猫眼电影榜单信息

扶醉桌前 提交于 2019-12-18 17:59:42

预期效果

在这里插入图片描述

代码实现

import requests
from requests.exceptions import RequestException
import re
import json


def get_one_page(url):
    try:
        response = requests.get(url,
                                headers={
                                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:57.0) Gecko/20100101 Firefox/57.0'}
                                )
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None

def parse_one_page(html):
    pattern = re.compile('<dd>.*?</dd>', re.S)
    results = re.findall(pattern, html)
    for result in results:
        sub_pattern = re.compile(
            '<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',
            re.S)
        sub_results = re.findall(sub_pattern, result)
        for sub_result in sub_results:
            yield {
                'index': sub_result[0],
                'image': sub_result[1],
                'title': sub_result[2],
                'actor': sub_result[3].strip()[3:],
                'time': sub_result[4].strip()[5:],
                'score': sub_result[5] + sub_result[6]
            }

def write_to_file(content):
    with open('maoyan_result.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')
        f.close()

def main(offset):
    url = 'http://maoyan.com/board/4?offset='+ str(offset)
    html = get_one_page(url)
    for sub_result in parse_one_page(html):
        print(sub_result)
        write_to_file(sub_result)

if __name__ == '__main__':
    for i in range(10):
        main(i*10)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!