浏览器抓取网页(puppeteergoogle团队出品的puppeteer和浏览器功能)
优采云 发布时间: 2021-09-18 04:21浏览器抓取网页(puppeteergoogle团队出品的puppeteer和浏览器功能)
木偶演员
GoogleChrome团队生产的puppeter是一个依靠nodejs和Chrome的自动化测试库。它最大的优点是可以处理网页中的动态内容,如JavaScript,并更好地模拟用户
一些网站反爬虫方法在一些JavaScript/Ajax请求中隐藏了部分内容,这使得直接获取a标记的方法无效。有些网站甚至会设置用户看不见的隐藏元素“陷阱”,脚本触发器被认为是机器。在这种情况下,木偶师的优势就突出了
可实现以下功能:
1.生成页面的截图和PDF
2.抓取spa并生成预渲染内容(即“SSR”)
3.自动表单提交、UI测试、键盘输入等
4.创建最新的自动化测试环境。使用最新的JavaScript和浏览器功能直接在最新版本的chrome中运行测试
5.捕获并跟踪您的网站时间线,以帮助诊断性能问题
开放源代码地址:[]1]
装置
npm i puppeteer
注意:首先安装nodejs并在nodejs文件的根目录下执行(同一级别的NPM文件)
铬将在安装过程中下载,约120m
花了两天(约10小时)的时间探索并绕过了大量的异步坑。作者对木偶演员和舞者有一定的掌握
长照片、抓拍blog文章List:
抓住blog文章
以CSDN博客为例,文章内容需要通过点击“读取全文”获取,这导致只能读取dom的脚本失效
/**
* load blog.csdn.net article to local files
**/
const puppeteer = require('puppeteer');
//emulate iphone
const userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1';
const workPath = './contents';
const fs = require("fs");
if (!fs.existsSync(workPath)) {
fs.mkdirSync(workPath)
}
//base url
const rootUrl = 'https://blog.csdn.net/';
//max wait milliseconds
const maxWait = 100;
//max loop scroll times
const makLoop = 10;
(async () => {
let url;
let countUrl=0;
const browser = await puppeteer.launch({headless: false});//set headless: true will hide chromium UI
const page = await browser.newPage();
await page.setUserAgent(userAgent);
await page.setViewport({width:414, height:736});
await page.setRequestInterception(true);
//filter to block images
page.on('request', request => {
if (request.resourceType() === 'image')
request.abort();
else
request.continue();
});
await page.goto(rootUrl);
for(let i= 0; iwindow.scrollTo(0, document.body.scrollHeight));
await page.waitForNavigation({timeout:maxWait,waitUntil: ['networkidle0']});
}catch(err){
console.log('scroll to bottom and then wait '+maxWait+'ms.');
}
}
await page.screenshot({path: workPath+'/screenshot.png',fullPage: true, quality :100, type :'jpeg'});
//#feedlist_id li[data-type="blog"] a
const sel = '#feedlist_id li[data-type="blog"] h2 a';
const hrefs = await page.evaluate((sel) => {
let elements = Array.from(document.querySelectorAll(sel));
let links = elements.map(element => {
return element.href
})
return links;
}, sel);
console.log('total links: '+hrefs.length);
process();
async function process(){
if(countUrl {
if (request.resourceType() === 'image')
request.abort();
else
request.continue();
});
await tab.goto(url);
//execute tap request
try{
await tab.tap('.read_more_btn');
}catch(err){
console.log('there\'s none read more button. No need to TAP');
}
let title = await tab.evaluate(() => document.querySelector('#article .article_title').innerText);
let contents = await tab.evaluate(() => document.querySelector('#article .article_content').innerText);
contents = 'TITLE: '+title+'\nURL: '+url+'\nCONTENTS: \n'+contents;
const fs = require("fs");
fs.writeFileSync(workPath+'/'+tab.url().substring(tab.url().lastIndexOf('/'),tab.url().length)+'.txt',contents);
console.log(title + " has been downloaded to local.");
await tab.close();
}catch(err){
console.log('url: '+tab.url()+' \n'+err.toString());
}finally{
process();
}
}
})();
执行过程
录音机可以在我的官方帐户中查看,屏幕截图如下:
执行结果
文章内容列表:
文章content:
结论
我认为由于nodejs使用JavaScript脚本语言,它当然可以处理web页面的JavaScript内容,但我没有找到合适/高效的库。直到找到木偶师,我才下定决心试水
换句话说,nodejs的异步性确实令人头痛。我已经花了10个小时写了几百行代码
您可以在代码中展开process()方法并使用async.eachseries。我使用的递归方法不是最佳解决方案
事实上,逐个处理是没有效率的。我最初编写了一个异步方法来关闭浏览器:
<p>let tryCloseBrowser = setInterval(function(){
console.log("check if any process running...")
if(countDown