Python爬取保存爱奇艺评分最高页电影信息

爱奇艺电影评分最高的几部电影是哪几部?用Python爬取保存下来

一,使用库

  1.requests

  2.re

  3.json

 

二,抓取html文件

def get_page(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.text
    return None

 

三,解析html文件

  我们需要的电影信息的部分如下图(评分,片名,主演):

 

 

   抓取到的html文件对应的代码:

 

 

 

   可以分析出,每部电影的信息都在一个<li>标签内,用正则表达式解析:

def parse_page(html):
    pattern = re.compile('<li.*?qy-mod-li.*?text-score">(.*?)<.*?title.*?>(.*?)<.*?title.*?>(.*?)<', re.S)
    items = re.findall(pattern, html)
    for item in items:#转换为字典形式保存
        yield {
            'score': item[0],
            'name': item[1],
            'actor': item[2].strip()[3:]#将‘主演:’去掉
        }

 

四,写入文件

def write_to_file(content):
    with open('result.txt', 'a', encoding='utf-8')as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')#将字典格式转换为字符串加以保存,并设置中文格式
        f.close()

 

五,调用函数

def main():
    url = 'https://list.iqiyi.com/www/1/-------------8-1-1-iqiyi--.html'
    html = get_page(url)
    for item in parse_page(html):
        print(item)
        write_to_file(item)

 

六,运行结果

 

 

 

 

七,完整代码

import json
import requests
import re


# 抓取html文件
# 解析html文件
# 存储文件


def get_page(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.text
    return None


def parse_page(html):
    pattern = re.compile('<li.*?qy-mod-li.*?text-score">(.*?)<.*?title.*?>(.*?)<.*?title.*?>(.*?)<', re.S)
    items = re.findall(pattern, html)
    for item in items:
        yield {
            'score': item[0],
            'name': item[1],
            'actor': item[2].strip()[3:]
        }


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


def main():
    url = 'https://list.iqiyi.com/www/1/-------------8-1-1-iqiyi--.html'
    html = get_page(url)
    for item in parse_page(html):
        print(item)
        write_to_file(item)


if __name__ == '__main__':
    main()

 

posted @ 2019-11-17 17:56  陈畅  阅读(609)  评论(1编辑  收藏  举报