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的简单爬虫代码

不得不说python的上手非常简单。在网上找了一下,大都是python2的帖子,于是随手写了个python3的。代码非常简单就不解释了,直接贴代码。 复制代码 代码如下:#test rd...

Python爬虫工程师面试问题总结

注:答案一般在网上都能够找到。 1.对if __name__ == 'main'的理解陈述 2.python是如何进行内存管理的? 3.请写出一段Python代码实现删除一个lis...

Python实现简易Web爬虫详解

简介: 网络爬虫(又被称为网页蜘蛛),网络机器人,是一种按照一定的规则,自动地抓信息的程序或者脚本。假设互联网是一张很大的蜘蛛网,每个页面之间都通过超链接这根线相互连接,那么我们的爬虫小...

简单的抓取淘宝图片的Python爬虫

写了一个抓taobao图片的爬虫,全是用if,for,while写的,比较简陋,入门作品。 从网页http://mm.taobao.com/json/request_top_list.h...

Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息示例

本文实例讲述了Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息。分享给大家供大家参考,具体如下: import time from multiprocessing i...