首页 > 解决方案 > Puppeteer 使用 xPath 返回 undefined (JS)

问题描述

我正在尝试抓取这个元素:在此处输入图像描述这个网站上

我的 JS 代码:

const puppeteer = require("puppeteer");

const url = 'https://magicseaweed.com/Bore-Surf-Report/1886/'
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const title = await page.$x('/html/body/div[1]/div[2]/div[2]/div/div[2]/div[2]/div[2]/div/div/div[1]/div/header/h3/div[1]/span[1]')
let text = await page.evaluate(res => res.textContext, title[0])
console.log(text) // UNDEFINED

文本未定义。这里有什么问题?谢谢。

标签: javascriptnode.jspuppeteer

解决方案


我认为您需要修复代码中的 1 或 2 个问题。

  1. 文本内容与文本上下文
  2. 路径

对于您想要的内容,xpath 应该是:

const title = await page.$x('/html/body/div[1]/div[2]/div[2]/div/div[2]/div[2]/div[2]/div/div/div[1]/div/div[1]/div[1]/div/div[2]/ul[1]/li[1]/text()')

并获取此内容:

const text = await page.evaluate(el => {
    return el.textContent.trim()
}, title[0])

请注意,您需要将 title[0] 作为参数发送给页面函数。

或者

如果您不需要使用 xpath,您似乎可以直接使用类名来查找元素:

const rating = await page.evaluate(() => {
    return $('.rating.rating-large.clearfix > li.rating-text')[0].textContent.trim()
})

推荐阅读