多看puppeteer 文档,中文地址:https://www.mofazhuan.com/puppeteer-doc-zh
1. 直接报错
internal/util.js:209
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'original', 'function');
^
TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function
at promisify (internal/util.js:209:11)
at Object.<anonymous> (/var/www/html/path/node_modules/extract-zip/index.js:11:18)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/var/www/html/path/node_modules/puppeteer/lib/BrowserFetcher.js:25:17)
解决办法: 更新nodejs 版本,越新越好。
2. chrome 版本与 puppeteer 版本适配
https://github.com/puppeteer/puppeteer/blob/master/docs/api.md 查看chrome版本与puppeteer版本对应表。executablePath对应chrome存放路径(这里是mac系统)
await puppeteer.launch({executablePath:'/Users/qx/Documents/myPuppeteer/chrome-mac/Chromium.app/Contents/MacOS/Chromium',headless:false});
3. 网页跳转,主动打开新链接,并切换tab获取当前page
const page2 = await browser.newPage(); #创建新页面
await page2.setDefaultNavigationTimeout(0) #取消超时30000秒报错
await page2.goto('https://example.com'); #打开新页面
const newPage = (await browser.pages())[2]; # browser.pages() 是目前打开的所有页面,包括一开始打开的页面,从0开始。
newPage 就是当前新页面的page对象
4. 获取元素属性值
单个元素属性值
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const text = await page.$eval('.text', el => el.textContent);
const html = await page.$eval('.main-container',e => e.outerHTML);
const html = await page.$eval('.main-container',e => e.innerText);
获取多个元素属性值
const liveidList = await newPage.$$eval('.item > a', elements => {
const ctn = elements.map(v => {
return v.href.split('liveId=')[1].split('&')[0];
});
return ctn;
});
5. newPage.evaluate 模拟页面滑动效果
async function autoScroll(page){
await page.evaluate(async () => {
console.log(window.scrollBy())
await new Promise((resolve, reject) => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if(totalHeight >= scrollHeight){
clearInterval(timer);
resolve();
}
}, 100);
});
});
}
6. 页面反爬虫技术,导致window.scroll方法不存在
找了很多资料,看到有人说设置window.navigator.webdriver 为undefined 就可以逃过爬虫检测,尝试未果,但还是记录一下。
const page = await browser.newPage();
#在页面打开之前设置navigator.webdriver为undefined,并提前保存window函数,之后使用定义的变量方法。
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
window._$scrollTo=window.scrollTo
window._$scrollBy=window.scrollBy
})
最后查看页面代码,最终发现问题所在。设置scrollTop = scrollHeight 页面滑动
await newPage.evaluate( () => {
#设置scrollTop = scrollHeight
document.getElementsByClassName("v-main")[0].scrollTop = document.getElementsByClassName("v-main")[0].scrollHeight
})