使用nodejs puppeteer框架实现登录网站,废话不多说,直接上代码
const puppeteer = require('puppeteer-extra')
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
//延迟函数
const sleep = time => new Promise(resolve =>{
setTimeout(resolve,time);
});
//下面所有都异步执行
(async() => {
const conf = {
headless: false,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
"--ignore-certificate-errors" //,
// '--proxy-server=${newProxyUrl}'
],
slowMo:1000,//设置浏览器每一步之间的时间间隔,单位毫秒
// executablePath: pathToExtension,
defaultViewport: {//默认的网页大小
width: 1300,
height: 900
}
}
puppeteer.use(StealthPlugin())
const browser = await puppeteer.launch(conf);//启动浏览器
const page = await browser.newPage();
await page.goto('http://shanzhi.spbeen.com/index');
await sleep(2000);
//选择a标签并且样式是btn btn-primary
const login_link_button = await page.$('a.btn.btn-primary');
await login_link_button.click();//点击到登录界面
await sleep(2000);
//输入用户名和密码
const username_input = await page.$('input#username');//#表示ID选择器
await username_input.type('demo1234');//输入
await sleep(2000);
const password_input = await page.$('input#memberPassword');//#表示ID选择器
await password_input.type('123456');//输入
await sleep(2000);
const submit_button = await page.$('button.btn.btn-primary');
await submit_button.click();
await sleep(2000);
//截图,是截图的页面的图片,并不是浏览器
await page.screenshot({path:'shanzhi_login_index.png'});
await sleep(5000);
await browser.close();
})();