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

Puppeteer定位指定FormData元素报错,求解决方法

Puppeteer爬取SEC网站时定位第18个FormData元素的问题解决

问题场景

使用Puppeteer爬取https://www.sec.gov/edgar/search/#/category=form-cat2时,需要获取页面中第18个类名为FormData的元素,但原代码中使用document.querySelector('.FormData')[17]定位时触发报错:

Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'innerText')

其他元素的定位逻辑正常,仅在获取目标FormData元素时出错。

错误原因

  • document.querySelector()方法只会返回匹配选择器的第一个元素,并非元素数组,因此使用[17]索引访问会直接得到undefined,后续读取innerText自然触发类型错误。
  • 若页面内容是动态加载的,可能在执行evaluate时第18个FormData元素还未渲染完成,导致元素集合长度不足,索引17对应的元素不存在。

解决步骤

  1. 替换元素选择方法:使用document.querySelectorAll('.FormData')获取所有匹配FormData类的元素,再通过索引[17]定位第18个元素(索引从0开始)。
  2. 增加等待逻辑:在执行元素提取前,等待目标元素加载完成,确保页面动态内容渲染完毕。

修正后的完整代码

// MODULES
const puppeteer = require("puppeteer");

// Url where we get and scrape the data from
const URL = "https://www.sec.gov/edgar/search/#/category=form-cat2";

(async () => {
    try {
        const chromeBrowser = await puppeteer.launch({ headless: true });
        const page = await chromeBrowser.newPage();
        await page.goto(URL, { timeout: 0 });

        // 等待第18个FormData元素加载完成
        await page.waitForFunction(() => document.querySelectorAll('.FormData').length >= 18, { timeout: 0 });

        const getInfo = await page.evaluate(() => {
            const secTableEN = document.querySelector(".table td.entity-name");
            const secTableFiled = document.querySelector(".table td.filed");
            // 获取所有FormData元素并定位第18个
            const formDataElements = document.querySelectorAll('.FormData');
            const secTableLinkPrice = formDataElements[17];

            return {
                secTableEN: secTableEN?.innerText || 'N/A',
                secTableFiled: secTableFiled?.innerText || 'N/A',
                secTableLinkPrice: secTableLinkPrice?.innerText || 'N/A',
            };
        });

        console.log(
            "Name: " + getInfo.secTableEN, '\n' +
            "Amount Purchased: " + getInfo.secTableLinkPrice, '\n'
        );

        await page.close();
        await chromeBrowser.close();
    } catch (e) {
        console.error(e)
    }
})();

额外优化说明

  • 加入可选链操作符?.:即使元素未找到,也不会抛出错误,而是返回'N/A',增强代码健壮性。
  • 使用waitForFunction精准等待:相比通用的元素等待,直接判断元素数量达标,确保目标元素已渲染,避免索引越界问题。

内容的提问来源于stack exchange,提问作者Jojo Amankwa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:55:14