Why does Puppeteer return CSS files wrapped in HTML?

Viewed 441

Gathering a CSS file with Puppeteer gives the content wrapped in HTML. Why is this? What must be done to get pure CSS instead?

For example:

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/newmusic/css/newmusic_min_1b1ebf56.css', {waitUntil: 'networkidle0'});

result = await page.content(); 

my expected result is:

.s-newmusic{position:fixed;.....

but the result is:

<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">.s-newmusic{position:fixed;.....

1 Answers

Puppeteer's page.content method returns the full HTML contents of the page (including the doctype). If you open the css file in chrome and open DevTools > Elements tab you will see that even in case of a simple text file (like css) there is HTML content. The actual content is wrapped inside a <pre> element the same way as puppeteer returned it to you. It has practical reasons: it makes rendering and visualization of text files unified in browsers.

You can get the text content of the css file's <body> with page.evaluate like this:

const result = await page.evaluate(body => body.innerText, await page.$('body'));

Output:

.s-newmusic{position:fixed;_position:absolute;width:0;height:50px;left:50%;z-index:100;font-family:arial,...
Related