Python requests + 正则表达式 猫眼电影top100 信息抓取

源代码:

# 请求异常的时候报错
from requests.exceptions import RequestException
import requests
import json
import time
import re


# 获取网页源代码
def get_one_page(url):
    try:
        headers = {
            'User-Agent':
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)'
        }
        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>.*?rd-index.*?">(.*?)</i>.*?data-src="(.*?)" alt.*?data-val="{movie.*?}">(.*?)</a>.*?<p class="star">(.*?)</p>.*?<p class="releasetime">(.*?)</p>.*?<i class="integer">(.*?).</i><.*?ss="fraction">(.*?)</i>.*?</dd>',
        re.S)
    # re.findall提取出所有的信息
    items = re.findall(pattern, html)
    for item in items:
        # yield方法可以将字典转化为字典
        yield {
            'index': item[0],
            'image': item[1],
            'title': item[2].strip(),
            'actor': item[3].strip()[3:],
            'time': item[4].strip()[5:],
            'score': item[5].strip() + item[6].strip()
        }


# 保存到文件
def write_to_file(content):
    # a代表追加的方式
    with open('result.txt', 'a', encoding='utf-8') as f:
        # json.dumps将python的字典格式转化为字符串进行写入
        # 指定ensure_ascii为false 可以保证输出的结果是中文形式
        f.write(json.dumps(content, ensure_ascii=False) + '\n')


def main(offset):
    url = 'https://maoyan.com/board/4?offset=' + str(offset)
    # 获取每一页的源代码
    html = get_one_page(url)
    # 用for循环提取每一页的需要信息 并打印保存
    for each in parse_one_page(html):
        print(each)
        write_to_file(each)


if __name__ == '__main__':
    # 用偏移量代表翻页
    for i in range(10):
        main(offset=i * 10)
        time.sleep(1)

截图:
1
2

ps: 有任何问题欢迎评论交流

猜你喜欢

转载自blog.csdn.net/qq_40258748/article/details/89606720