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

yipeiwu_com6年前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设计】。

相关文章

Python进阶之使用selenium爬取淘宝商品信息功能示例

本文实例讲述了Python进阶之使用selenium爬取淘宝商品信息功能。分享给大家供大家参考,具体如下: # encoding=utf-8 __author__ = 'Jonny'...

Python3爬虫学习之爬虫利器Beautiful Soup用法分析

Python3爬虫学习之爬虫利器Beautiful Soup用法分析

本文实例讲述了Python3爬虫学习之爬虫利器Beautiful Soup用法。分享给大家供大家参考,具体如下: 爬虫利器Beautiful Soup 前面一篇说到通过urllib.re...

玩转python爬虫之正则表达式

玩转python爬虫之正则表达式

面对大量杂乱的代码夹杂文字我们怎样把它提取出来整理呢?下面就开始介绍一个十分强大的工具,正则表达式! 1.了解正则表达式 正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特...

Python爬虫爬取一个网页上的图片地址实例代码

Python爬虫爬取一个网页上的图片地址实例代码

本文实例主要是实现爬取一个网页上的图片地址,具体如下。 读取一个网页的源代码: import urllib.request def getHtml(url): html=urll...

python 中xpath爬虫实例详解

python 中xpath爬虫实例详解

案例一: 某套图网站,套图以封面形式展现在页面,需要依次点击套图,点击广告盘链接,最后到达百度网盘展示页面。 这一过程通过爬虫来实现,收集百度网盘地址和提取码,采用xpath爬虫技术...