[英]How to get HTML element text using puppeteer
This question has definitely been asked multiple times, but I've looked everywhere and none of the answers worked for me.这个问题肯定已经被问过很多次了,但是我到处找,没有一个答案对我有用。
So I have the following Div:所以我有以下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>
I am trying to get the text in the parent div: Showing 1 to 20 of 761,871 entries我正在尝试获取父 div 中的文本:显示 761,871 个条目中的 1 到 20 个
I tried:我试过了:
const text = await page.$eval('div#dt-card-entry_info.dataTables_info', el => el.textContent)
and also并且
const text = await page.evaluate(() => {
const el = document.querySelector('#dt-card-entry_info')
return el.innerText
})
From Browser Console, this works:从浏览器控制台,这有效:
$('#dt-card-entry_info').text()
and also this:还有这个:
$('#dt-card-entry_info')[0].innerText
or this:或这个:
$('#dt-card-entry_info')[0].textContent
You can use您可以使用
document.getElementById document.getElementById
You want the text content so use:你想要文本内容,所以使用:
var res = document.getElementById('dt-card-entry_info').textContent;
Your method can be used like this then:您的方法可以像这样使用:
const text = await page.evaluate(() => {
const el = document.getElementById('dt-card-entry_info');
return el.textContent;
})
I don't like the await pageEval in the const
def, so I would change it outside the scope of the eval.我不喜欢
const
def 中的 await pageEval,所以我会在 eval 的 scope 之外更改它。
This is because the pageEval is a promise, so you will need in turn to return a promise of the string content.这是因为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);
You can it working here: https://jsfiddle.net/9s4zxvLk/你可以在这里工作: https://jsfiddle.net/9s4zxvLk/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.