如何使用 Apify 抓取动态加载列表和单个页面?

时间:2021-01-08 23:28:43

标签: web-scraping apify

如何使用 Apify 的功能生成完整的 URL 列表,以便在用户向底部滚动时按顺序批量添加项目的索引页面进行抓取?换句话说,它是动态加载/无限滚动,而不是按钮点击操作。

具体来说,这个页面 - https://www.provokemedia.com/agency-playbook 除了最初显示的 13 个条目之外,我无法让它识别任何其他内容。

这些元素似乎位于每个段的底部,每次添加段时 display: none 都会更改为 display: block。原始源代码中没有“style”标签,只能通过 DevTools Inspector 看到。

<div class="text-center" id="loader" style="display: none;">
    <h5>Loading more ...</h5>
</div>

这是我的网络爬虫的基本设置...

起始网址:

https://www.provokemedia.com/agency-playbook
{
  "label": "START"
}

链接选择器:

div.agencies div.column a

伪网址:

https://www.provokemedia.com/agency-playbook/agency-profile/[.*]
{
  "label": "DETAIL"
}

页面功能:

async function pageFunction(context) {
    const { request, log, skipLinks } = context;
    // request: holds info about current page
    // log: logs messages to console
    // skipLinks: don't enqueue matching Pseudo Links on current page
    // >> cf. https://docs.apify.com/tutorials/apify-scrapers/getting-started#new-page-function-boilerplate



    // *********************************************************** //
    //                          START page                         //
    // *********************************************************** //
    if (request.userData.label === 'START') {
        log.info('Store opened!');
        // Do some stuff later.
    }


    // *********************************************************** //
    //                          DETAIL page                        //
    // *********************************************************** //
    if (request.userData.label === 'DETAIL') {
        log.info(`Scraping ${request.url}`);
        await skipLinks();
        // Do some scraping.
        return {
            // Scraped data.
        }
    }
}

想必,在 START 内容中,我需要确保显示整个列表以进行排队,而不仅仅是 13 个。

我已经通读了 Apify 的文档,包括关于“Waiting for dynamic content”的文档。 await waitFor('#loader'); 似乎是一个不错的选择。

我在 START 部分添加了以下内容...

    let timeoutMillis; // undefined
    const loadingThing = '#loader';
    while (true) {
        log.info('Waiting for the "Loading more" thing.');
        try {
            // Default timeout first time.
            await waitFor(loadingThing, { timeoutMillis });
            // 2 sec timeout after the first.
            timeoutMillis = 2000;
        } catch (err) {
            // Ignore the timeout error.
            log.info('Could not find the "Loading more thing", '
                + 'we\'ve reached the end.');
            break;
        }
        log.info('Going to load more.');
        // Scroll to bottom, to expose more
        // $(loadingThing).click();
        window.scrollTo(0, document.body.scrollHeight);
    }

但是没有用...

2021-01-08T23:24:11.186Z INFO  Store opened!
2021-01-08T23:24:11.189Z INFO  Waiting for the "Loading more" thing.
2021-01-08T23:24:11.190Z INFO  Could not find the "Loading more thing", we've reached the end.
2021-01-08T23:24:13.393Z INFO  Scraping https://www.provokemedia.com/agency-playbook/agency-profile/gci-health

与其他网页不同,当我在 DevTools 控制台中手动输入 window.scrollTo(0, document.body.scrollHeight); 时,此页面不会滚动到底部。

然而,当在Console中手动执行时,这段代码添加了一个小的延迟 - setTimeout(function(){window.scrollBy(0,document.body.scrollHeight)}, 1); - 如发现in this question - 确实每次都跳到底部......

如果我添加行来替换上面while循环的最后一行,但是,循环仍然记录它找不到元素。

我在使用这些方法吗?不知道该往哪个方向转。

1 个答案:

答案 0 :(得分:1)

@LukášKřivka 在 How to make the Apify Crawler to scroll full page when web page have infinite scrolling? 的回答为我的回答提供了框架...

总结:

  • 创建一个函数来促使强制滚动到页面底部
  • 获取所有元素

详情:

  • while 循环中,滚动到页面底部。
  • 等一下。新内容需要 5 秒才能呈现。
  • 记录目标链接选择器的数量,以获取信息。
  • 直到不再加载项目。

仅当 pageFunction 正在检查索引页面(例如,用户数据中的 START/LISTING 等任意页面名称)时才调用此函数。

async function pageFunction(context) {



    // *********************************************************** //
    //                      Few utilities                          //
    // *********************************************************** //
    const { request, log, skipLinks } = context;
    // request: holds info about current page
    // log: logs messages to console
    // skipLinks: don't enqueue matching Pseudo Links on current page
    // >> cf. https://docs.apify.com/tutorials/apify-scrapers/getting-started#new-page-function-boilerplate
    const $ = jQuery;





    // *********************************************************** //
    //                Infinite scroll handling                     //
    // *********************************************************** //
    // Here we define the infinite scroll function, it has to be defined inside pageFunction
    const infiniteScroll = async (maxTime) => { //maxTime to wait

        const startedAt = Date.now();
        // count items on page
        let itemCount = $('div.agencies div.column a').length; // Update the selector

        while (true) {

            log.info(`INFINITE SCROLL --- ${itemCount} items loaded --- ${request.url}`)
            // timeout to prevent infinite loop
            if (Date.now() - startedAt > maxTime) {
                return;
            }
            // scroll page x, y
            scrollBy(0, 9999);
            // wait for elements to render
            await context.waitFor(5000); // This can be any number that works for your website
            // count items on page again
            const currentItemCount = $('div.agencies div.column a').length; // Update the selector

            // check for no more
            // We check if the number of items changed after the scroll, if not we finish
            if (itemCount === currentItemCount) {
                return;
            }
            // update item count
            itemCount = currentItemCount;

        }

    }






    // *********************************************************** //
    //                          START page                         //
    // *********************************************************** //
    if (request.userData.label === 'START') {
        log.info('Store opened!');
        // Do some stuff later.

        // scroll to bottom to force load of all elements
        await infiniteScroll(60000); // Let's try 60 seconds max

    }


    // *********************************************************** //
    //                          DETAIL page                        //
    // *********************************************************** //
    if (request.userData.label === 'DETAIL') {
        log.info(`Scraping ${request.url}`);
        await skipLinks();
        
        // Do some scraping (get elements with jQuery selectors)

        return {
            // Scraped data.
        }
    }
}