使用Puppeteer爬取网站时遇TypeError:无法读取null的textContent属性
Puppeteer爬取报错:Cannot read properties of null (reading 'textContent') 分析与解决
问题详情
使用Puppeteer爬取网站时遇到错误:Error [TypeError]: Cannot read properties of null (reading 'textContent'),尝试移除textContent返回undefined,添加User-Agent后问题仍未解决。相关代码如下:
const puppeteer = require("puppeteer"); const getQuotes = async () => { // Start a Puppeteer session with: // - a visible browser (`headless: false` - easier to debug because you'll see the browser in action) // - no default viewport (`defaultViewport: null` - website page will in full width and height) const browser = await puppeteer.launch({ headless: false, defaultViewport: null, }); // Open a new page const page = await browser.newPage(); await page.setExtraHTTPHeaders({ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' }); // On this new page: // - open the "http://quotes.toscrape.com/" website // - wait until the dom content is loaded (HTML is ready) await page.goto("https://www.axs.com/browse/music", { waitUntil: "networkidle2"}); const quotes = await page.evaluate(()=>{ //fetch the first element with class 'quote' const quoteList = document.querySelectorAll('#page-relative-block > div > div.layout-column--primary-lg > div > div > div:nth-child(2) > div > div:nth-child(2)'); return Array.from(quoteList).map((quote)=>{ //fetch the sub-elements of each element with the class quotes const text = quote.querySelector('.headliner').textContent; const author = quote.querySelector('.supporting').textContent; return {text, author} }); }); console.log(quotes) await browser.close(); }; // Start the scraping getQuotes();
可能原因及解决方法
1. 元素选择器过于脆弱
你使用的链式CSS选择器#page-relative-block > div > div.layout-column--primary-lg > div > div > div:nth-child(2) > div > div:nth-child(2)完全依赖页面DOM层级结构,只要网站调整任何一个元素的嵌套关系、类名或位置,这个选择器就会失效,导致quoteList为空或者获取到错误的元素。
解决:
改用更稳定的选择器,比如直接定位包含目标内容的容器类名(打开浏览器开发者工具查看实际元素类名),例如:
const quoteList = document.querySelectorAll('.event-card'); // 替换为页面实际的容器类名
2. 未等待动态元素完全渲染
waitUntil: "networkidle2"仅表示网络请求基本完成,但页面上的动态内容(比如通过JS异步加载的演出信息)可能还没渲染完成,此时执行page.evaluate会找不到目标元素。
解决:
在执行爬取逻辑前,显式等待目标子元素加载完成:
// 在page.goto之后添加 await page.waitForSelector('.headliner', { timeout: 5000 }); // 等待.headliner元素出现,超时5秒
3. 子元素可能不存在
部分quote元素中可能没有.headliner或.supporting类的子元素,直接调用textContent会因为querySelector返回null而报错。
解决:
添加空值判断,避免直接访问null的属性:
return Array.from(quoteList).map((quote)=>{ const textEl = quote.querySelector('.headliner'); const authorEl = quote.querySelector('.supporting'); const text = textEl ? textEl.textContent.trim() : '无标题'; const author = authorEl ? authorEl.textContent.trim() : '无表演者'; return {text, author} });
内容的提问来源于stack exchange,提问作者techmystic
相关产品推荐
相关产品推荐

