最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Puppeteer: How to get parentNode without using evaluate? - Stack Overflow

programmeradmin1浏览0评论

With Puppeteer, I know how to use evaluate for having some properties like parentNode or previousSibling:

let id = await page.evaluate(() => {
    let wantedHref = $('li a').filter(
        function (index) {
            return $(this).text().includes("Text that I Want");
        })[0];
    //get parentNode
    let id = wantedHref.parentNode.parentNode.parentNode.id;
    //get  previousSibling
    let expandIcon = wantedLink.parentNode.parentNode.previousSibling;
    expandIcon.click();
    return id;
});

I would like to know how I could retrieve these types of properties without using evaluation.

Could you help me, please?

With Puppeteer, I know how to use evaluate for having some properties like parentNode or previousSibling:

let id = await page.evaluate(() => {
    let wantedHref = $('li a').filter(
        function (index) {
            return $(this).text().includes("Text that I Want");
        })[0];
    //get parentNode
    let id = wantedHref.parentNode.parentNode.parentNode.id;
    //get  previousSibling
    let expandIcon = wantedLink.parentNode.parentNode.previousSibling;
    expandIcon.click();
    return id;
});

I would like to know how I could retrieve these types of properties without using evaluation.

Could you help me, please?

Share Improve this question edited Mar 15, 2020 at 7:18 Nmk 1,3192 gold badges14 silver badges28 bronze badges asked Mar 2, 2020 at 16:12 PipoPipo 5,6417 gold badges37 silver badges71 bronze badges 5
  • The underlying CDP has DOM.describeNode mand so it should be possible to use it in Puppeteer as well. See the documentation I've linked - the mand returns a Node response with parentId inside which you can query in another DOM.describeNode or other mands that accept a node id. To find the original node you can use DOM.querySelector. – woxxom Commented Mar 2, 2020 at 16:15
  • Why don't you want to use evaluate? – hardkoded Commented Mar 2, 2020 at 16:29
  • @hardkoded I don't want to use evaluate cause it is more difficult to debug and to make pause , and anyway I would like to do this type of operation in several way – Pipo Commented Mar 2, 2020 at 16:38
  • @hardkoded I want to get all div with a specific class and get all id of their parent – Pipo Commented Mar 2, 2020 at 17:05
  • You could do a mix, use $$ to get all the elements, and then an evaluate to get the parent of each element. – hardkoded Commented Mar 2, 2020 at 18:50
Add a ment  | 

1 Answer 1

Reset to default 7

elementHandle.getProperty('parentNode')

You can use elementHandle.getProperty() to obtain the parentNode property of the current ElementHandle:

const current_element = await page.$('#example');
const parent_node = await current_element.getProperty('parentNode');

await parent_node.click();
发布评论

评论列表(0)

  1. 暂无评论