zoukankan      html  css  js  c++  java
  • 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) + '
    ')#将字典格式转换为字符串加以保存,并设置中文格式
            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) + '
    ')
            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()
  • 相关阅读:
    JZOJ 4298. 【NOIP2015模拟11.2晚】我的天
    JZOJ 4314. 【NOIP2015模拟11.4】老司机
    JZOJ 4313. 【NOIP2015模拟11.4】电话线铺设
    SP2416 DSUBSEQ
    JZOJ 2020.08.03【NOIP提高组】模拟 &&【NOIP2015模拟11.5】
    Android一些网站介绍
    http://www.androiddevtools.cn/
    Eclipse的安装使用
    JDK环境配置
    关于appcompat_v7的说明
  • 原文地址:https://www.cnblogs.com/chenchang-rjgc/p/11877301.html
Copyright © 2011-2022 走看看