微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ajax分析与爬取实战

爬取目标

一个示例网站,其链接为:https://spa1.scrape.center/ ,改示例网站的数据请求是通过Ajax完成的,页面内容是通过JavaScript渲染出来的,页面加载如下图所示:

分析步骤

  • 分析页面数据的加载逻辑
  • 用requests实现Ajax数据的爬取
  • 将每部电影的数据分别保存到MysqL数据库

页面分析

如果我们直接通过requests.get(url)来获取页面,结果如下,可以发现返回内容并非是浏览器渲染的源码,说明我们看到的整个页面都是由JavaScript和CSS文件渲染得到的,浏览器执行了HTML引用的JavaScript文件,JavaScript通过调用一些数据加载和页面渲染方法,才最终呈现了完整页面


所以,打开浏览器开发者模式,点击网络模块-XHR。重新加载页面,切换下一页时,可以发现浏览器发送了一些请求,查看相应内容,就是页面内容数据

代码实例

# -*- UTF-8 -*-
"""
@File:spa1_179.py
@Description:
@Author:echohye
@Date:2022/01/31 20:08
"""

import json
import pyMysqL
import requests

urls = [
    f'https://spa1.scrape.center/api/movie/?limit=10&offset={page * 10}'
    for page in range(10)
]

# 获取url对应源码
def craw(url):
    r = requests.get(url)
    return r.text


# 解析源码
def parse(html):
    obj = json.loads(html)['results']
    return obj

# 保存数据
def save_data():
    # 'id': 1,
    # 'name': '霸王别姬',
    # 'alias': 'farewell My Concubine',
    # 'cover': 'https://p0.meituan.net/movie/ce4da3e03e655b5b88ed31b5cd7896cf62472.jpg@464w_644h_1e_1c',
    # 'categories': ['剧情', '爱情'],
    # 'published_at': '1993-07-26',
    # 'minute': 171,
    # 'score': 9.5,
    # 'regions': ['中国内地', '中国香港']}
    db = pyMysqL.Connect(host='localhost', user='root', password='zhy123', port=3306, db='spiders')
    cursor = db.cursor()
    table_sql = "create table if not exists ajax_p179(id int not null,name varchar(255) not null,alias varchar(255),cover varchar(255)" \
                ",categories varchar(255), published_at varchar(255),minute varchar(255),score double,regions varchar(255))"
    cursor.execute(table_sql)
    for url in urls:
        try:
            for result in parse(craw(url)):
                sql = "insert into ajax_p179(id,name,alias,cover,categories,published_at,minute,score,regions) " \
                      f"values({result.get('id')},\"{result.get('name')}\",\"{result.get('alias')}\",'{result.get('cover')}',\"{result.get('categories')}\"," \
                      f"'{result.get('published_at')}','{result.get('minute')}',{result.get('score')},\"{result.get('regions')}\")"
                cursor.execute(sql)
                db.commit()

        except Exception as e:
            print(e.args)
            db.rollback()
        print("successful")
    db.close()


if __name__ == '__main__':
    save_data()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐