Python 爬虫实战:批量抓取应用商店分类应用

在移动互联网数据分析、竞品调研、行业报告制作等场景中,应用商店的 APP 分类数据是核心数据源之一。无论是分析某一赛道的应用分布,还是监控同类 APP 的核心指标,通过 Python 爬虫批量抓取应用商店分类应用数据,都是高效且低成本的解决方案。本文将以主流安卓应用商店为例,从环境搭建、爬虫设计、数据解析到存储落地,完整讲解如何实现应用商店分类应用的批量爬取,帮助你快速掌握实战爬虫开发的核心逻辑。

一、爬虫开发前期准备

1.1 技术选型与环境搭建

本次实战选用 Python 作为开发语言,核心依赖以下库:

  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">requests</font>:发送 HTTP 请求获取网页 / 接口数据;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">BeautifulSoup4</font>:解析 HTML 页面提取目标数据;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">pandas</font>:数据清洗与 Excel 存储;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">fake-useragent</font>:生成随机 User-Agent,规避基础反爬;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">time</font>:设置请求间隔,降低服务器压力。

1.2 目标分析与反爬注意事项

本文以某公开安卓应用商店的「工具类」分类为例(实际可替换为任意分类),核心抓取字段包括:APP 名称、下载量、评分、简介、所属分类。

爬取前需注意:

  1. 遵守网站<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">robots.txt</font>协议,避免高频请求;
  2. 仅用于学习研究,勿将数据用于商业用途;
  3. 加入随机请求间隔、随机 User-Agent,模拟正常用户访问;
  4. 若遇到验证码、IP 封禁,及时停止爬取,切勿对抗。

二、核心代码实现

2.1 基础配置与请求函数封装

首先封装请求函数,实现「发送请求 - 获取响应 - 异常处理」的基础逻辑,同时加入反爬策略:

python

运行

plain 复制代码
import requests
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import pandas as pd
import time
import random

# 初始化UserAgent生成器
ua = UserAgent()

def get_html(url, timeout=10):
    """
    发送GET请求获取页面HTML
    :param url: 目标URL
    :param timeout: 请求超时时间
    :return: 页面HTML文本/None
    """
    headers = {
        "User-Agent": ua.random,  # 随机User-Agent
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Referer": "https://www.baidu.com/"  # 模拟来路
    }
    try:
        # 随机延迟1-3秒,避免高频请求
        time.sleep(random.uniform(1, 3))
        response = requests.get(url, headers=headers, timeout=timeout)
        response.raise_for_status()  # 抛出HTTP状态码异常
        response.encoding = response.apparent_encoding  # 自动识别编码
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"请求失败:{url},错误信息:{e}")
        return None

2.2 解析页面提取分类应用数据

接下来编写解析函数,从页面 HTML 中提取目标字段。以某应用商店分类页为例(URL 格式为<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">https://xxx.com/category/tool?p={page}</font>,page 为页码),通过 BeautifulSoup 定位元素:

python

运行

plain 复制代码
def parse_app_list(html):
    """
    解析应用商店分类页,提取APP数据
    :param html: 页面HTML文本
    :return: 解析后的APP数据列表
    """
    app_list = []
    if not html:
        return app_list
    
    soup = BeautifulSoup(html, "html.parser")
    # 定位APP列表项(需根据实际页面结构调整CSS选择器)
    app_items = soup.select("div.app-item")
    
    for item in app_items:
        try:
            # 提取核心字段(需根据实际页面标签调整)
            app_name = item.select_one("h3.app-name").get_text(strip=True) if item.select_one("h3.app-name") else "未知"
            download_count = item.select_one("span.download-num").get_text(strip=True) if item.select_one("span.download-num") else "0"
            score = item.select_one("span.score").get_text(strip=True) if item.select_one("span.score") else "0"
            intro = item.select_one("p.app-intro").get_text(strip=True) if item.select_one("p.app-intro") else "无简介"
            category = item.select_one("span.category").get_text(strip=True) if item.select_one("span.category") else "工具类"
            
            # 构造字典存储单条APP数据
            app_info = {
                "APP名称": app_name,
                "下载量": download_count,
                "评分": score,
                "简介": intro,
                "所属分类": category
            }
            app_list.append(app_info)
        except Exception as e:
            print(f"解析单条APP数据失败,错误信息:{e}")
            continue
    return app_list

2.3 批量爬取与数据存储

编写主函数,实现多页数据批量爬取,并将结果存储为 Excel 文件:

python

运行

plain 复制代码
def batch_crawl(category_url, start_page=1, end_page=5):
    """
    批量爬取指定分类的多页应用数据
    :param category_url: 分类页基础URL(需包含{p}占位符)
    :param start_page: 起始页码
    :param end_page: 结束页码
    :return: 所有爬取的APP数据列表
    """
    all_app_data = []
    for page in range(start_page, end_page + 1):
        # 拼接当前页URL
        current_url = category_url.format(p=page)
        print(f"正在爬取第{page}页:{current_url}")
        
        # 获取页面HTML并解析
        html = get_html(current_url)
        app_data = parse_app_list(html)
        
        if app_data:
            all_app_data.extend(app_data)
            print(f"第{page}页爬取完成,共{len(app_data)}条数据")
        else:
            print(f"第{page}页无数据,停止爬取")
            break  # 无数据则终止后续页码爬取
    
    return all_app_data

if __name__ == "__main__":
    # 替换为实际的应用商店分类页URL(需包含{p}占位符)
    # 示例:https://xxx.com/category/tool?p={p}
    CATEGORY_URL = "https://your-target-url.com/category/tool?p={p}"
    # 爬取1-5页数据
    app_data = batch_crawl(CATEGORY_URL, start_page=1, end_page=5)
    
    if app_data:
        # 将数据转换为DataFrame并存储为Excel
        df = pd.DataFrame(app_data)
        # 去重(避免重复爬取)
        df = df.drop_duplicates(subset=["APP名称"], keep="first")
        # 保存到本地
        df.to_excel("应用商店工具类APP数据.xlsx", index=False, encoding="utf-8")
        print(f"爬取完成!共获取{len(df)}条有效数据,已保存至「应用商店工具类APP数据.xlsx」")
    else:
        print("未爬取到任何数据,请检查URL或页面结构")

三、代码适配与优化

3.1 页面结构适配说明

上述代码中的 CSS 选择器(如<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">div.app-item</font><font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">h3.app-name</font>)是通用示例,实际使用时需根据目标应用商店的页面结构调整:

  1. 打开目标应用商店分类页,按 F12 打开开发者工具;
  2. 定位 APP 列表项的外层标签,替换<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">app_items = soup.select("div.app-item")</font>中的选择器;
  3. 依次定位 APP 名称、下载量等字段的标签,修改解析函数中的选择器。

3.2 进阶优化策略

  1. 异步爬取 :使用<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">aiohttp</font>替代<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">requests</font>,实现异步请求,提升爬取效率(适合大量页码);
  2. IP 代理池 :若遇到 IP 封禁,可接入代理池,在请求时添加<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">proxies</font>参数;推荐使用亿牛云爬虫代理
  3. 断点续爬:将已爬取的页码和数据实时保存,避免程序中断后重新爬取;
  4. 数据校验:添加字段格式校验(如评分需为 0-5 的数值),提升数据质量。

四、常见问题与解决方案

  1. 页面解析为空 :检查 CSS 选择器是否匹配目标页面,或目标页面是否为动态加载(若为动态加载,需使用<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">Selenium</font><font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">Playwright</font>渲染页面);
  2. 请求被拒绝:增加请求间隔、更换 User-Agent,或检查是否被网站拉黑 IP;
  3. Excel 中文乱码 :确保<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">to_excel</font>时指定<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">encoding="utf-8"</font>,或使用<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">openpyxl</font>引擎:<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">df.to_excel("xxx.xlsx", index=False, engine="openpyxl")</font>
  4. 数据重复 :通过<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">drop_duplicates</font>去重,或爬取前记录已爬取的 APP 名称。

五、合规与伦理说明

  1. 爬取数据前需确认目标网站的用户协议,禁止爬取非公开数据;
  2. 控制爬取频率,避免给目标服务器造成压力;
  3. 爬取的数据仅用于学习、研究,禁止用于商业售卖或恶意分析;
  4. 若网站明确禁止爬虫,需立即停止操作。
相关推荐
亿牛云爬虫专家2 小时前
解耦之美:将业务逻辑从繁杂的代理异常捕获中抽离
python·爬虫代理·业务逻辑·代理ip·异常捕获·try-except·重试算法
N盒2 小时前
【WhisperX+M2M100】快速视频转字幕工具
python·pip
mingshili2 小时前
[架构设计] pypubsub 底层实现机制与高性能替代方案
python·架构设计
电商API&Tina2 小时前
item_video-获得淘宝商品视频 API||商品API
java·大数据·服务器·数据库·人工智能·python·mysql
YMWM_2 小时前
PyArmor介绍
python
1941s2 小时前
08-智能体开发实战指南(八):UI 集成与生产部署
人工智能·python·langchain
阿Y加油吧2 小时前
测试文章法撒发撒
python
core5122 小时前
深入浅出 Milvus 向量数据库:从核心原理到 Python 实战指南
数据库·python·milvus·向量数据库·语义检索
不懒不懒2 小时前
【使用逻辑回归(Logistic Regression)算法对预处理后的数据集(平均值填充)进行分类任务训练与评估】
算法·分类·逻辑回归