You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Zyte浏览器自动化点击含JavaScript的下一页链接?

问题

常规爬虫可处理带真实URL的下一页链接,但遇到下一页链接仅含href="#"、通过JavaScript触发跳转/加载的场景时,无法直接提取有效URL并使用response.follow_all。Zyte官方教程的《处理JavaScript》章节仅提供滚动加载示例,缺少点击下一页触发JS渲染的实操案例。

尝试了一段代码(见下方),但困惑于Zyte浏览器自动化必须发起请求,无法像onclick事件那样直接触发点击动作,希望找到解决方案。

import scrapy
from scrapy import Request

class BooksToScrapeSpider(scrapy.Spider):
    name = "books_toscrape"
    start_urls = [
        "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html"
    ]

    def parse(self, response):
        # Extract book data
        for book in response.css("article.product_pod"):
            yield {
                "name": book.css("h3 a::attr(title)").get(),
                "price": book.css(".price_color::text").get(),
            }

        # Find the "next" link
        next_page = response.css("li.next a::attr(href)").get()
        if next_page:
            self.logger.info(f"Found next page: {next_page}")
            yield Request(
                # response.urljoin(next_page),
                "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html#",
                meta={
                    "zyte_api_automap": {
                        "browserHtml": True,
                        "actions": [
                            {
                                "action": "click",
                                "selector": {"type": "css", "value": "li.next a"},
                            },
                            {
                                "action": "waitForSelector",
                                "selector": {
                                    "type": "css",
                                    "value": "li.previous a",
                                },
                            },
                        ],
                    }
                },
                callback=self.parse,
            )
        else:
            self.logger.info("No next page found")
解决方案

Zyte浏览器自动化确实需要基于请求的页面上下文执行动作,但可以通过复用当前页面URL的方式实现类似onclick的触发效果,具体调整如下:

核心思路

href="#"本质是指向当前页面的锚点,请求该URL会在浏览器中加载当前页面,之后即可在页面上下文中执行点击动作触发JS逻辑,无需硬写固定URL。同时需调整等待逻辑,确保JS加载的新内容完全渲染后再进行数据提取。

优化后的代码

import scrapy
from scrapy import Request

class BooksToScrapeSpider(scrapy.Spider):
    name = "books_toscrape"
    start_urls = [
        "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html"
    ]

    def parse(self, response):
        # 提取书籍数据
        for book in response.css("article.product_pod"):
            yield {
                "name": book.css("h3 a::attr(title)").get(),
                "price": book.css(".price_color::text").get(),
            }

        # 查找下一页按钮
        next_btn = response.css("li.next a")
        if next_btn:
            self.logger.info("找到下一页按钮,准备触发JS跳转")
            yield Request(
                # 自动解析锚点URL,复用当前页面地址
                response.urljoin(next_btn.attrib["href"]),
                meta={
                    "zyte_api_automap": {
                        "browserHtml": True,
                        "actions": [
                            # 点击下一页按钮
                            {
                                "action": "click",
                                "selector": {"type": "css", "value": "li.next a"},
                            },
                            # 等待新内容加载完成:以书籍元素为目标,确保数据渲染
                            {
                                "action": "waitForSelector",
                                "selector": {"type": "css", "value": "article.product_pod"},
                                "timeout": 5000  # 超时时间5秒,可按需调整
                            }
                        ],
                    }
                },
                callback=self.parse,
            )
        else:
            self.logger.info("无更多下一页")

关键调整说明

  1. URL处理:恢复使用response.urljoin(next_btn.attrib["href"]),自动解析href="#"为当前页面URL,避免硬编码带来的灵活性问题。
  2. 等待逻辑:将等待目标从li.previous a改为article.product_pod,确保新加载的书籍内容完全渲染后再进入下一轮解析,适配更多页面场景。如果是JS触发页面跳转(而非AJAX加载),可替换为waitForNavigation动作。
  3. 流程合理性:通过请求当前页面锚点的方式,在浏览器上下文内执行点击动作,完美模拟用户点击href="#"按钮的行为。

内容的提问来源于stack exchange,提问作者Ralf Zosel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:10:00