使用 Playwright 获取列表元素列表

Getting a list of list elements using Playwright

我正在尝试编写一个应用程序,它将转到亚马逊并在页面上获取图书列表。我正在使用 Playwright 作为工具。我可以找到正确的部分,但无法获得图书清单。在线查看示例似乎使用 page.$$(selector) 但是当我尝试这样做时,我得到一个空数组。在 $$ 上找到此信息 and here. Reading the docs,这似乎是正确的调用,因为所有列表元素都具有相同的 class 名称。我不知道我做错了什么,有什么建议吗?

到目前为止,这是我的代码;

const AMAZON_KINDLE_EBOOK_STORE_URL = 'https://www.amazon.com/Best-Sellers-Kindle-Store-eBooks/zgbs/digital-text/154606011/ref=zg_bs_nav_kstore_1_kstore/';
(async () => {
    const browser = await chromium.launch();
    try {
        const amazonPage = await browser.newPage();
        await amazonPage.goto(AMAZON_KINDLE_EBOOK_STORE_URL);

        await amazonPage.waitForSelector('"Best Sellers in"');
        await amazonPage.click('"Self-Help"');
        await amazonPage.click('"Creativity"')

        const books = await amazonPage.$$('li[class="zg-item-immersion"]');
        console.log(books);
    } finally {
        await browser.close();
    }
})();

对于选择器我也试过很多方法;

似乎唯一的问题是 Plawright 太快了,你没有等待那些元素 li[class="zg-item-immersion"]

我调试了脚本并且选择器没问题,所以对于这一行,returns 50 个元素句柄:

const { chromium } = require('playwright');

const AMAZON_KINDLE_EBOOK_STORE_URL = 'https://www.amazon.com/Best-Sellers-Kindle-Store-eBooks/zgbs/digital-text/154606011/ref=zg_bs_nav_kstore_1_kstore/';
(async () => {
    const browser = await chromium.launch({ headless: false});
    try {
        const amazonPage = await browser.newPage();
        await amazonPage.goto(AMAZON_KINDLE_EBOOK_STORE_URL);

        await amazonPage.waitForSelector('"Best Sellers in"');
        await amazonPage.click('"Self-Help"');

        await Promise.all([
            amazonPage.waitForNavigation(),
            amazonPage.click('"Creativity"')
        ]);
        
        const books = await amazonPage.$$('li[class="zg-item-immersion"]');
        console.log(books);
    } finally {
        await browser.close();
    }
})();

你也许可以做你在上面几行中为选择器所做的事情:

const { chromium } = require('playwright');

const AMAZON_KINDLE_EBOOK_STORE_URL = 'https://www.amazon.com/Best-Sellers-Kindle-Store-eBooks/zgbs/digital-text/154606011/ref=zg_bs_nav_kstore_1_kstore/';
(async () => {
    const browser = await chromium.launch({ headless: false});
    try {
        const amazonPage = await browser.newPage();
        await amazonPage.goto(AMAZON_KINDLE_EBOOK_STORE_URL);

        await amazonPage.waitForSelector('"Best Sellers in"');
        await amazonPage.click('"Self-Help"');
        await amazonPage.click('"Creativity"')

        await amazonPage.waitForSelector('li[class="zg-item-immersion"]');
        const books = await amazonPage.$$('li[class="zg-item-immersion"]');
        console.log(books);
    } finally {
        await browser.close();
    }
})();

它也是这样工作的。