gpt4 book ai didi

javascript - 如何使用 puppeteer 获取 HTML 元素文本

转载 作者:行者123 更新时间:2023-12-05 03:44:53 31 4
gpt4 key购买 nike

这个问题肯定已经被问过很多次了,但我到处都看了,没有一个答案对我有用。

所以我有以下 Div:

<div class="dataTables_info" id="dt-card-entry_info" role="status" aria-live="polite">
Showing 1 to 20 of 761,871 entries
<span class="select-info">
<span class="select-item">
1 row selected
</span>
<span class="select-item">

</span>
<span class="select-item">

</span>
</span>
</div>

我正在尝试获取父 div 中的文本:显示 761,871 个条目中的 1 到 20 个

我试过:

const text = await page.$eval('div#dt-card-entry_info.dataTables_info', el => el.textContent)

还有

 const text = await page.evaluate(() => {
const el = document.querySelector('#dt-card-entry_info')
return el.innerText
})

从浏览器控制台,这有效:

$('#dt-card-entry_info').text()

还有这个:

$('#dt-card-entry_info')[0].innerText

或者这个:

$('#dt-card-entry_info')[0].textContent

最佳答案

你可以使用

document.getElementById

你想要文本内容,所以使用:

var res = document.getElementById('dt-card-entry_info').textContent;

你的方法可以这样使用:

const text = await page.evaluate(() => {
const el = document.getElementById('dt-card-entry_info');
return el.textContent;
})

我不喜欢 const def 中的 await pageEval,所以我会在 eval 范围之外更改它。

这是因为pageEval是一个promise,所以你需要反过来返回一个promise的字符串内容。 Read More Here

let text = '';
await page.evaluate(() => {
const el = document.getElementById('dt-card-entry_info');
text = el.textContent;
})
console.log(text);

你可以在这里工作:https://jsfiddle.net/9s4zxvLk/

关于javascript - 如何使用 puppeteer 获取 HTML 元素文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66173666/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com