Puppeteer
npm install puppeteer安装
goto等待网页加载成功,默认设置的是30秒时间,超过时间会崩溃,
javascript
// domcontentloaded 这个事件在初始的HTML文档被完全加载和解析完成之后,且无需等待样式表、图片和子框架完成加载时触发。
// load load事件在页面所有资源(比如图片和样式表)都下载和加载完成后触发。
await page.goto('https://www.doba.com',{ waitUntil: 'load' });1
2
3
2
3
获取按钮href元素
javascript
// 使用page.evaluate来获取href属性,因为href是DOM元素的一个属性
const loginBtn = await page.$('.login-txt');
// 如果找到了按钮,获取其href属性
let href;
if (loginBtn) {
// 使用page.evaluate来获取href属性,因为href是DOM元素的一个属性
href = await page.evaluate(button => {
return button.href;
}, loginBtn);
console.log(`The href of the button is: ${href}`);
} else {
console.log('Button not found');
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
获取登录框
javascript
//登录账号
await page.type('#loginForm_loginName', 'HOOCHEN@aliyun.com',{
delay: 1000
});
await page.type('#loginForm_password', '!Wxy181220',{
delay: 1000
});
let login = await page.$('#doba-retailer-login')1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
模拟用户滚动到最下面
javascript
const puppeteer = require('puppeteer');
(async () => {
// 启动浏览器
const browser = await puppeteer.launch();
// 创建一个新页面
const page = await browser.newPage();
// 导航到指定的 URL
await page.goto('https://example.com');
// 滑动到页面底部的函数
async function scrollToBottom() {
await page.evaluate(async () => {
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);
});
});
}
// 调用滑动到页面底部的函数
await scrollToBottom();
// 在这里可以执行其他页面操作,例如截图、提取页面内容等
// 关闭页面
await page.close();
// 关闭浏览器
await browser.close();
})();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40