Actor picture

Cainiao Tracking Actor

nguyennk91/cainiao-tracking-actor

No credit card required

Author's avatarKen Nguyen
  • Modified
  • Users15
  • Runs28
Actor picture

Cainiao Tracking Actor

Based on the apify/actor-node-chrome:v0.21.10 Docker image (see docs).

const Apify = require('apify');
const request = require('request-promise');

Apify.main(async () => {
    // Get input of your actor
    const input = await Apify.getInput();
    console.log('Tracking Code:');
    console.dir(input.trackingCode);

    const requestList = new Apify.RequestList({
        sources: [{ url: 'https://global.cainiao.com/detail.htm?mailNoList='+input.trackingCode }],
    });
    await requestList.initialize();

    const crawler = new Apify.PuppeteerCrawler({
        requestList,
        handlePageFunction: async ({ page, request }) => {
            // This function is called to extract data from a single web page
            // 'page' is an instance of Puppeteer.Page with page.goto(request.url) already called
            // 'request' is an instance of Request class with information about the page to load
            await page
            .waitForSelector('#waybill_list_val_box');
            const element = await page.$("#waybill_list_val_box");
            const trackingRaw = await page.evaluate(element => element.textContent, element);
            console.log('Tracking Raw:');
            console.dir(trackingRaw);
            
            const parsedTracking = JSON.parse(trackingRaw);
        
            console.log('Tracking Detail:');
            console.dir(parsedTracking);
            // Save the data to dataset.
            await Apify.setValue('OUTPUT', parsedTracking);
        },
        handleFailedRequestFunction: async ({ request }) => {
            // This function is called when the crawling of a request failed too many times
            await Apify.pushData({
                url: request.url,
                succeeded: false,
                errors: request.errorMessages,
            });
        },
    });

    await crawler.run();
});