javascript - 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
文本未定义。这里有什么问题?谢谢。
解决方案
我认为您需要修复代码中的 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()
})
推荐阅读
- excel - 计算在 VBA 上填充数据的 Excel 表格行数
- r - 时间段 R 的条件总和
- typescript - CRA - 动态 redux-thunk 的 AppState 类型失败为“未知”
- typescript - 使用两个 for 循环查找重复项
- python - 匹配固定长度的字符和数字并在 Python 中出现一次
- flutter - 如何在没有 FutureBuilder 的情况下监听一堆 Futures?
- excel - 在多个范围内替换#Ref
- java - 使用日期值迭代 JSON 对象
- swift - 确定 Admob 的测试设备
- javascript - 如何更改输入内闪烁光标的大小