python爬虫之正则表达式爬取猫眼前100的电影(七)

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


def get_one_page(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'
        }
        response = requests.get(url, headers=headers)
        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.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
                         + '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
                         + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
    items = re.findall(pattern, html)
    for item in items:
        yield {
            'index': item[0],
            'image': item[1],
            'title': item[2],
            'actor': item[3].strip()[3:],#通过F12打开网页,network工作台就自然可以理解,也就是把不需要的字给删除了
            'time': item[4].strip()[5:],#同理
            'score': item[5] + item[6]#同理
        }


def write_to_file(content):
    with open('result.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(100):
        main(offset=i * 10)
        time.sleep(1)

分析:

1.首先需要获取html源代码,即我们使用requests.get()方法来获取,同时判断是否时状态码是否200,在进行打印源代码。也就是我们get_one_page函数
2. (1)获取了源代码以后,我们就需要根据正则表达式来获取我们想要的东西,这里我们要的时排名,图片,电影名,导演,时间,以及评分。
(2)通过re.compile方法返回一个匹配对象,在通过find_all()方法,返回字典,通过遍历来使得更加美观,更加结构化
(3)获得了需要的东西之后,我们就可以将获得的东西存入文档里面,这里我们用到了json库中的dumps方法可以使得中文能够打印的出来,关键在于ensure_ascii=False参数、
(4)说明:这里的offset参数时一个偏移量,https://maoyan.com/board/4?offset=10,这个网址中offset为10,就是第二页,如果时第三页,则offset就为20,以此类推,因此我们可以用字符串拼接的方法将offset拼接到url中去,打印除更多的页数中的电影信息

爬取的结果:

在这里插入图片描述

发布了63 篇原创文章 · 获赞 12 · 访问量 4046

猜你喜欢

转载自blog.csdn.net/qq_45353823/article/details/104228044