Python爬取爱奇艺电影信息代码实例

yipeiwu_com5年前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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3实战之爬虫抓取网易云音乐的热门评论

Python3实战之爬虫抓取网易云音乐的热门评论

前言 之前刚刚入门python爬虫,有大概半个月时间没有写python了,都快遗忘了。于是准备写个简单的爬虫练练手,我觉得网易云音乐最优特色的就是其精准的歌曲推荐和独具特色的用户评论,于...

Python3爬虫爬取百姓网列表并保存为json功能示例【基于request、lxml和json模块】

Python3爬虫爬取百姓网列表并保存为json功能示例【基于request、lxml和json模块】

本文实例讲述了Python3爬虫爬取百姓网列表并保存为json功能。分享给大家供大家参考,具体如下: python3爬虫之爬取百姓网列表并保存为json文件。这几天一直在学习使用pyth...

Python爬虫实现全国失信被执行人名单查询功能示例

Python爬虫实现全国失信被执行人名单查询功能示例

本文实例讲述了Python爬虫实现全国失信被执行人名单查询功能。分享给大家供大家参考,具体如下: 一、需求说明 利用百度的接口,实现一个全国失信被执行人名单查询功能。输入姓名,查询是否在...

学习Python selenium自动化网页抓取器

直接入正题---Python selenium自动控制浏览器对网页的数据进行抓取,其中包含按钮点击、跳转页面、搜索框的输入、页面的价值数据存储、mongodb自动id标识等等等。 1、首...

python爬取指定微信公众号文章

本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下 该方法是依赖于urllib2库来完成的,首先你需要安装好你的python环境,然后安装urllib...