Last active
February 10, 2019 08:02
-
-
Save joaofnds/76a0601be316c08e9ce3a7dec9ba1398 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import fetch from "node-fetch"; | |
| import cheerio from "cheerio"; | |
| const TRACKING_NUMBER = ""; | |
| (async () => { | |
| const content = await getTrackingResponse(); | |
| const $ = cheerio.load(content, { | |
| normalizeWhitespace: true, | |
| decodeEntities: false | |
| }); | |
| const data = $("table.listEvent.sro tbody tr") | |
| .map((_, el) => { | |
| const tr = $(el); | |
| const firstTD = tr.find("td:nth-child(1)"); | |
| const [date, locale] = decodeTimeAndLocale(firstTD); | |
| const secondTD = tr.find("td:nth-child(2)"); | |
| const [event, description] = decodeEventAndDescription(secondTD); | |
| return { date, locale, event, description }; | |
| }) | |
| .get(); | |
| console.log(data); | |
| })(); | |
| async function getTrackingResponse() { | |
| const response = await fetch( | |
| "https://www2.correios.com.br/sistemas/rastreamento/resultado_semcontent.cfm", | |
| { | |
| credentials: "include", | |
| headers: { | |
| accept: | |
| "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", | |
| "accept-language": "en-US,en;q=0.9,pt;q=0.8", | |
| "cache-control": "max-age=0", | |
| "content-type": "application/x-www-form-urlencoded", | |
| "upgrade-insecure-requests": "1" | |
| }, | |
| referrerPolicy: "no-referrer-when-downgrade", | |
| body: `Objetos=${TRACKING_NUMBER}`, | |
| method: "POST", | |
| mode: "cors" | |
| } | |
| ); | |
| return response.text(); | |
| } | |
| function decodeTimeAndLocale(td) { | |
| const timeAndLoc = td | |
| .html() | |
| .split("<br>") | |
| .map(sentence => sentence.replace(/\s/gim, "")); | |
| const time = `${timeAndLoc[0]} ${timeAndLoc[1]}`; | |
| return [time, timeAndLoc[2]]; | |
| } | |
| function decodeEventAndDescription(td) { | |
| const event = td.find("strong").text(); | |
| const description = td | |
| .html() | |
| .split("<br>")[1] | |
| .split(" ") | |
| .map(sentence => sentence.replace(/\s/gim, "")) | |
| .join(" "); | |
| return [event, description]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment