0

我用我想要抓取的 URL 设置了一个爬虫,演员正在工作,我用 cookie/屏幕截图示例进行了测试。我只是在将 cookie 从演员传递到爬网时遇到问题:

const Apify = require('apify');

Apify.main(async () => {
    const input = await Apify.getValue('INPUT');

    const browser = await Apify.launchPuppeteer();
    const page = await browser.newPage();
    await page.goto('http://xy.com/login');

    // Login
    await page.type('#form_user_login_email', input.username);
    await page.type('#form_user_login_password', input.password);
    await page.evaluate(() => { document.querySelectorAll('.btn-full-width')[1].click(); });
    await page.waitForNavigation();

    // Get cookies
    const cookies = await page.cookies();

    // Use cookies in other tab or browser
    //const page2 = await browser.newPage();
    //await page2.setCookie(...cookies);
    // Get cookies after login

    const apifyClient = Apify.client;
    // call crawler with cookies
    const execution = await apifyClient.crawlers.startExecution({
    crawlerId: 'mhi',
    settings: {
      cookies: cookies
    }
    });

    console.log('Done.');

    console.log('Closing Puppeteer...');
    await browser.close();

});

我认为cookie没有通过,因为Crawler没有登录。

4

1 回答 1

1

您的代码应该可以工作。也许您可以尝试设置cookiesPersistence : 'OVER_CRAWLER_RUNS'为设置。如果您不确定 cookie 是否通过,您可以使用 API 端点https://api.apify.com/v1/user_id/crawlers/crawler_id?token=api_apify_token&executionId=execution_id进行检查。

但是您不需要将cookie传递给爬虫,您可以使用Apify SDK直接在actor中对其进行爬取。您只需要在 PuppeteerCrawler 中覆盖 goto 函数,您可以在其中设置 cookie。检查puppeterCrawler 的文档

const Apify = require('apify');

Apify.main(async () => {
    const input = await Apify.getValue('INPUT');

    const browser = await Apify.launchPuppeteer();
    const page = await browser.newPage();
    await page.goto('http://xy.com/login');

    // Login
    await page.type('#form_user_login_email', input.username);
    await page.type('#form_user_login_password', input.password);
    await page.evaluate(() => { document.querySelectorAll('.btn-full-width')[1].click(); });
    await page.waitForNavigation();

    // Get cookies
    const cookies = await page.cookies();

    const crawler = new Apify.PuppeteerCrawler({
        // puppeteer crawler options
        gotoFunction: async ({ request, page }) => {
            await page.setCookie(cookies);
            return page.goto(request.url);
        }
    });

    await crawler.run();

    console.log('Done.');

    console.log('Closing Puppeteer...');
    await browser.close();
});
于 2019-05-10T10:28:58.320 回答