我正在做
const last = await page.$('.item:last-child')
现在我很想根据最后一个元素获取前面的元素。 IE
const prev = last.$.prev()
关于如何做到这一点有什么想法吗?
Thanks!
你应该使用previousElementSibling https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling inside evaluateHandle https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatehandlepagefunction-args, 像这样:
const prev = await page.evaluateHandle(el => el.previousElementSibling, last);
这是完整的示例:
const puppeteer = require('puppeteer');
const html = `
<html>
<head></head>
<body>
<div>
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
</div>
</body>
</html>`;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(`data:text/html,${html}`);
const last = await page.$('.item:last-child');
const prev = await page.evaluateHandle(el => el.previousElementSibling, last);
console.log(await (await last.getProperty('innerHTML')).jsonValue()); // item 3
console.log(await (await prev.getProperty('innerHTML')).jsonValue()); // item 2
await browser.close();
})();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)