Scrapling v0.3.0 新手完全指南:从零到爬虫高手

0 阅读8分钟

是不是经常看到别人用Python轻松抓取网页数据,而自己还在手动复制粘贴?别担心,今天认识一个超好用的工具——Scrapling v0.3.0,让网页抓取变得像刷抖音一样简单!

一、先了解网页的“内部结构”

在学爬虫之前,我们要先明白网页是怎么组成的。看下面这个简单的商品页面:

<!-- 这是一个商品页面的HTML代码 -->
<!DOCTYPE html>
<html>
<head>
    <title>手机专卖店</title>
</head>
<body>
    <div class="product-page">
        <!-- 商品标题区域 -->
        <div class="product-header">
            <h1 id="product-title">iPhone 15 Pro Max 512GB</h1>
            <div class="product-sku">商品编号:APP-IPHONE-001</div>
        </div>
        
        <!-- 价格区域 -->
        <div class="price-section">
            <span class="current-price">¥9,999</span>
            <span class="original-price">¥10,999</span>
            <span class="discount-tag">立省1,000元</span>
        </div>
        
        <!-- 商品信息表格 -->
        <table class="spec-table">
            <tr>
                <th>颜色</th>
                <td>钛金属原色</td>
            </tr>
            <tr>
                <th>存储容量</th>
                <td>512GB</td>
            </tr>
            <tr>
                <th>网络</th>
                <td>5G全网通</td>
            </tr>
        </table>
        
        <!-- 用户评论 -->
        <div class="reviews">
            <h3>用户评价 (128条)</h3>
            <div class="review-item" data-review-id="1">
                <span class="user-name">张三</span>
                <span class="rating">★★★★★</span>
                <p class="comment">手机很流畅,拍照效果超棒!</p>
            </div>
            <div class="review-item" data-review-id="2">
                <span class="user-name">李四</span>
                <span class="rating">★★★★☆</span>
                <p class="comment">电池续航比想象中好,就是有点重</p>
            </div>
        </div>
        
        <!-- 相关推荐 -->
        <div class="related-products">
            <h3>猜你喜欢</h3>
            <div class="related-item">
                <a href="/product/airpods-pro">AirPods Pro 2代</a>
                <span class="price">¥1,899</span>
            </div>
            <div class="related-item">
                <a href="/product/iphone-15">iPhone 15 256GB</a>
                <span class="price">¥7,999</span>
            </div>
        </div>
    </div>
</body>
</html>

这就是网页的“源代码” 。就像看房子的结构图一样,HTML告诉浏览器哪里是标题、哪里是价格、哪里是图片。

二、Scrapling是什么?

想象一下,你想从这个网页获取:

  • 商品名称
  • 当前价格
  • 原价
  • 产品规格
  • 用户评价

用传统方法,你需要:

  1. 打开网页
  2. 用鼠标选中“iPhone 15 Pro Max 512GB”
  3. 按Ctrl+C复制
  4. 打开Excel粘贴
  5. 重复128次... 😫

用Scrapling,你只需要:

from scrapling.fetchers import Fetcher

# 一句话:给我这个页面的数据
page = Fetcher.get('https://phone-shop.com/iphone-15-pro')

# 自动提取信息
product_name = page.css('#product-title::text').get()  # 商品名称
price = page.css('.current-price::text').get()         # 当前价格
specs = page.css('.spec-table td::text').getall()      # 所有规格

Scrapling就是你的“网页数据收割机” ,你告诉它要什么,它就自动帮你收集整理。

三、Scrapling v0.3.0 三大神奇功能

功能1:会话保持 - 像真实用户一样“记住”状态

生活中的比喻:你去超市购物,收银员给你一张会员卡。下次再来,刷卡就知道你是谁,能享受什么优惠。

网页中的场景:很多网站需要登录才能看内容,登录后网站用“会话”记住你是谁。

from scrapling.fetchers import StealthySession

# 创建会话(就像拿到会员卡)
with StealthySession as session:

    # 第一步:登录
    login_page = session.fetch(
        login_url,
        headless=False,
        network_idle=True,
        timeout=60000,
        page_action=login_action
    )

    print("✓ 登录操作完成")

    # 第二步:访问需要登录的页面
    # 会话会自动带上登录状态,就像刷会员卡一样
    profile = session.fetch('https://example.com/my-profile')
    orders = session.fetch('https://example.com/my-orders')

    print(f"欢迎回来,{profile.css('.user-name::text').get()}!")
    print(f"你有 {len(orders.css('.order-item'))} 个订单")

实际例子:抓取需要登录的课程网站

<!-- 登录后才能看到的课程页面 -->
<div class="course-list">
    <div class="course" data-course-id="101">
        <h3>Python零基础入门</h3>
        <p>已学习:<span class="progress">85%</span></p>
        <a href="/course/101/video/1" class="continue-btn">继续学习</a>
    </div>
    <div class="course" data-course-id="102">
        <h3>网页抓取实战</h3>
        <p>已学习:<span class="progress">45%</span></p>
        <a href="/course/102/video/3" class="continue-btn">继续学习</a>
    </div>
</div>
# 用会话保持功能抓取学习进度
with StealthySession as session:
    # 先登录(假设已经有登录状态)

    # 访问课程页面
    courses_page = session.fetch('https://study.com/my-courses')

    courses = []
    for course in courses_page.css('.course'):
        course_info = {
            'name': course.css('h3::text').get(),
            'progress': course.css('.progress::text').get(),
            'continue_url': course.css('.continue-btn').attr('href')
        }
        courses.append(course_info)

    print("你的学习进度:")
    for c in courses:
        print(f"- {c['name']}: {c['progress']} 完成")

功能2:自动绕过Cloudflare - 穿墙术

生活中的比喻:有些商店门口有保安,看到可疑的人就不让进。Scrapling的StealthyFetcher就像给你一套“正装”,让保安以为你是VIP客户。

技术解释:Cloudflare是很多网站用的防护系统,能识别机器人并阻止访问。

from scrapling.fetchers import StealthyFetcher

# 普通方法(可能被阻止)
# page = Fetcher.get('https://protected-site.com')  # ❌ 可能失败

# 隐身模式(绕过检测)
page = StealthyFetcher.fetch(
    'https://protected-site.com',
    headless=True,  # 使用无头浏览器
    solve_cloudflare=True  # 自动解决Cloudflare验证
)

# 现在可以正常抓取数据了
data = page.css('.content::text').getall()
print(f"成功获取 {len(data)} 条数据")

实际例子:抓取有Cloudflare保护的论坛

<!-- 有Cloudflare保护的论坛页面 -->
<div class="forum-container">
    <div class="post" data-post-id="12345">
        <div class="post-header">
            <span class="author">技术小白</span>
            <span class="time">2小时前</span>
        </div>
        <div class="post-content">
            <h4>Scrapling怎么绕过Cloudflare?</h4>
            <p>最近在学爬虫,遇到有Cloudflare的网站就抓不到了...</p>
        </div>
        <div class="post-stats">
            <span class="likes">👍 24</span>
            <span class="replies">💬 8</span>
        </div>
    </div>
</div>
# 用隐身模式抓取论坛帖子
try:
    # 尝试用隐身模式
    forum_page = StealthyFetcher.fetch(
        'https://tech-forum.com/python',
        solve_cloudflare=True,
        headless=True
    )
    
    # 提取帖子信息
    posts = []
    for post in forum_page.css('.post'):
        post_data = {
            'author': post.css('.author::text').get(),
            'time': post.css('.time::text').get(),
            'title': post.css('h4::text').get(),
            'content': post.css('.post-content p::text').get(),
            'likes': post.css('.likes::text').get(),
            'replies': post.css('.replies::text').get()
        }
        posts.append(post_data)
    
    print(f"成功抓取 {len(posts)} 个帖子")
    
except Exception as e:
    print(f"抓取失败: {e}")
    print("尝试调整隐身设置...")
    # 可以尝试其他设置

四、安装Scrapling v0.3.0(超简单)

方法1:用pip安装(推荐)

# 打开命令行(Windows按Win+R,输入cmd,回车)
# 输入以下命令:

pip install scrapling --upgrade

# 如果需要完整功能
pip install "scrapling[all]"

# 安装浏览器驱动
scrapling install

方法2:验证安装

# 新建一个test.py文件,输入以下代码:
import scrapling
print(f"Scrapling版本: {scrapling.__version__}")

# 运行:python test.py
# 应该看到:Scrapling版本: 0.3.0

五、完整实战:抓取电商网站商品

让我们用Scrapling v0.3.0的所有新功能,完整抓取一个电商网站:
伪代码

from scrapling.fetchers import StealthySession
from scrapling.parser import Parser
import json
import time

class EcommerceCrawler:
    """电商网站抓取器"""
    
    def __init__(self):
        # 创建隐身会话
        self.session = StealthySession(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            headers={
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Referer': 'https://www.google.com/'
            }
        )
        self.all_products = []
    
    def fetch_category(self, category_url, category_name):
        """抓取一个分类的商品"""
        print(f"正在抓取 {category_name} 分类...")
        
        # 使用隐身模式,绕过可能的防护
        page = self.session.fetch(
            category_url,
            solve_cloudflare=True,
            headless=True
        )
        
        # 找到所有商品
        products = page.css('.product-item')
        print(f"找到 {len(products)} 个商品")
        
        for i, product in enumerate(products, 1):
            product_info = self.extract_product_info(product, category_name)
            if product_info:
                self.all_products.append(product_info)
            
            # 显示进度
            if i % 10 == 0:
                print(f"  已处理 {i}/{len(products)} 个商品")
            
            # 礼貌延迟,避免被屏蔽
            time.sleep(0.5)
    
    def extract_product_info(self, product_element, category):
        """从商品元素提取信息"""
        try:
            # 使用各种选择器提取数据
            info = {
                'category': category,
                'name': product_element.css('.product-name::text').get(),
                'price': self.clean_price(product_element.css('.price::text').get()),
                'original_price': self.clean_price(
                    product_element.css('.original-price::text').get()
                ),
                'image_url': product_element.css('img').attr('src'),
                'product_url': product_element.css('a').attr('href'),
                'rating': product_element.css('.rating').attr('data-score'),
                'reviews': product_element.css('.review-count::text').get()
            }
            
            # 清理数据
            info = {k: v.strip() if isinstance(v, str) else v 
                   for k, v in info.items()}
            
            return info
            
        except Exception as e:
            print(f"提取商品信息时出错: {e}")
            return None
    
    def clean_price(self, price_text):
        """清理价格文本"""
        if not price_text:
            return None
        # 移除货币符号和逗号
        return price_text.replace('¥', '').replace(',', '').strip()
    
    def save_results(self, format='both'):
        """保存结果"""
        timestamp = time.strftime('%Y%m%d_%H%M%S')
        
        if format in ['json', 'both']:
            with open(f'products_{timestamp}.json', 'w', encoding='utf-8') as f:
                json.dump(self.all_products, f, indent=2, ensure_ascii=False)
            print(f"✅ JSON数据已保存: products_{timestamp}.json")
        
        if format in ['csv', 'both']:
            import csv
            with open(f'products_{timestamp}.csv', 'w', newline='', encoding='utf-8') as f:
                if self.all_products:
                    writer = csv.DictWriter(f, fieldnames=self.all_products[0].keys())
                    writer.writeheader()
                    writer.writerows(self.all_products)
            print(f"✅ CSV数据已保存: products_{timestamp}.csv")
        
        print(f"总共抓取 {len(self.all_products)} 个商品")
    
    def print_summary(self):
        """打印统计摘要"""
        if not self.all_products:
            print("没有抓取到商品")
            return
        
        print("\n📊 抓取统计:")
        print(f"总商品数: {len(self.all_products)}")
        
        # 按价格统计
        prices = [float(p['price']) for p in self.all_products if p['price']]
        if prices:
            avg_price = sum(prices) / len(prices)
            max_price = max(prices)
            min_price = min(prices)
            
            print(f"平均价格: ¥{avg_price:.2f}")
            print(f"最高价格: ¥{max_price:.2f}")
            print(f"最低价格: ¥{min_price:.2f}")
        
        # 按分类统计
        categories = {}
        for p in self.all_products:
            cat = p.get('category', '未知')
            categories[cat] = categories.get(cat, 0) + 1
        
        print("分类分布:")
        for cat, count in categories.items():
            print(f"  {cat}: {count} 个商品")

# 使用示例
if __name__ == "__main__":
    # 创建抓取器
    crawler = EcommerceCrawler()
    
    # 定义要抓取的分类
    categories = {
        '手机': 'https://example-shop.com/category/phones',
        '笔记本': 'https://example-shop.com/category/laptops',
        '耳机': 'https://example-shop.com/category/headphones'
    }
    
    # 抓取每个分类
    for name, url in categories.items():
        crawler.fetch_category(url, name)
        print()  # 空行
    
    # 保存结果
    crawler.save_results('both')
    
    # 打印统计
    crawler.print_summary()

六、Scrapling的终端命令(不用写代码!)

Scrapling v0.3.0 最酷的功能之一:不用写Python代码也能抓取数据!

1. 快速抓取单个页面

# 在命令行直接运行
scrapling extract https://example.com

# 使用隐身模式
scrapling extract stealthy-fetch https://example.com

# 保存结果到文件
scrapling extract https://example.com --output data.json

2. 交互式Shell(像聊天一样抓取)

# 启动交互式Shell
scrapling shell https://example-shop.com

# 然后在Shell中可以直接测试:
>>> page.css('.product-name::text').getall()
['商品1', '商品2', '商品3']

>>> page.css('.price::text').getall()
['¥199', '¥299', '¥399']

七、常见问题解答

Q1:我完全不懂编程,能学会吗?

能! ​ Scrapling的设计就是为了让新手也能用。你可以:

  1. 先用终端命令体验
  2. 复制文章中的例子修改
  3. 用AI功能让AI帮你写代码

Q2:抓取数据违法吗?

看情况! ​ 要遵守:

  1. 查看网站的robots.txt
  2. 不要抓取个人隐私
  3. 控制抓取频率
  4. 用于学习和研究
  5. 遵守网站的使用条款

Q3:遇到反爬虫怎么办?

Scrapling v0.3.0 已经内置了解决方案:

反爬虫类型Scrapling解决方案
需要登录使用StealthySession保持会话
Cloudflare防护使用StealthyFetcher
频率限制添加time.sleep()延迟

Q4:数据抓下来怎么用?

你可以:

  1. 保存为JSON/CSV,用Excel打开分析
  2. 导入到数据库
  3. 用Python做数据分析
  4. 制作可视化图表
  5. 监控价格变化

八、学习路径建议

第1周:熟悉基础

# 每天练习一个例子
# Day1: 抓取标题
page.css('title::text').get()

# Day2: 抓取所有链接
page.css('a::attr(href)').getall()

# Day3: 抓取表格数据
page.css('table td::text').getall()

# Day4: 保存数据到文件
# Day5: 处理多个页面

第2周:实战项目

  1. 抓取天气预报
  2. 监控商品价格
  3. 收集新闻头条
  4. 下载网站图片

第3周:高级功能

  1. 学习会话保持
  2. 绕过反爬虫
  3. 使用AI辅助
  4. 优化抓取速度

九、资源推荐

学习网站

  • Scrapling官方文档- 最全的文档
  • W3School HTML教程- 学习HTML基础
  • 菜鸟教程Python- Python基础

练习网站

  • httpbin.org- 测试用的网站
  • books.toscrape.com- 专门练习爬虫的网站
  • quotes.toscrape.com- 名言网站,适合练习

十、现在就开始!

不要等到"学会Python"再开始,用Scrapling边用边学:

# 你的第一个爬虫程序
from scrapling.fetchers import Fetcher

# 1. 找一个你感兴趣的网站
url = "https://httpbin.org/html"

# 2. 获取页面
page = Fetcher.get(url)

# 3. 提取标题
title = page.css('h1::text').get()
print(f"页面标题: {title}")

# 4. 提取所有段落
paragraphs = page.css('p::text').getall()
for i, p in enumerate(paragraphs, 1):
    print(f"段落{i}: {p[:50]}...")  # 只显示前50个字