0

so im scraping a web and i need to use a specific cookies but i dont know how to exactly use "fetch"

    const url="https://www.example.com";
    let response = await fetch(url),
        html = await response.text();

    let $ = cheerio.load(html)

    var example= $('.exampleclass').text();  

Now i can scrape the web but in case i would have to use a specific cookies i dont know how to put in on the fetch.

In python was something like that

response = requests.get(url, headers=headers, cookies=cookies)

Thank you!

crs
  • 1
  • 1

1 Answers1

0

You can add the cookies on the headers on node-fetch, I've made a helper function that you can use for your purposes:

const cookieMaker = object => {
    const cookie = [];
    for (const [key, value] of Object.entries(object)) {
        cookie.push(`${key}=${value}`);
    }
    return cookie.join('; ');
};

const fetchText = async (url, cookie) => {
    const r = await fetch(url, {
        headers: {
            Cookie: cookieMaker(cookie),
        },
    });
    return await r.text();
};

fetchText('http://someurl.com', { token: 'abc', myValue: 'def' });
Shahriar Shojib
  • 657
  • 7
  • 14