1-1 click-type

  1. var btn = await page.$("#btn") //找到某个元素
  2. await btn.click() //点击事件
  3. await btn.type() //用户输入事件
  1. const puppeteer = require("puppeteer");
  2. const url = "https://www.baidu.com";
  3. (async ()=>{
  4. const browser = await puppeteer.launch({
  5. headless:false, //模拟浏览器行为
  6. defaultViewport:null, //可视区域最大化
  7. args: ['--start-maximized'] //浏览器窗口最大化
  8. });
  9. const page = await browser.newPage();
  10. await page.goto(url)
  11. var input = await page.$("#kw");
  12. await input.type("hello world")
  13. var btn = await page.$("#su")
  14. await btn.click()
  15. })();
  1. var content = await page.$eval('#su',ele=>ele.value);
  2. # $eval()获取元素的内容

1-2 模拟键盘回车事件

  1. await page.keyboard.press('Enter');

1-3 处理多个元素

  1. waitForSelector() //等待选择器加载
  2. $$eval() //处理多个元素的内容,获取的是数组
  1. const puppeteer = require("puppeteer");
  2. const url = "http://www.kuwo.cn/search/list?key=你";
  3. (async () => {
  4. const browser = await puppeteer.launch({
  5. defaultViewport: null, //可视区域最大化
  6. });
  7. const page = await browser.newPage();
  8. await page.goto(url)
  9. var input = await page.$(".search");
  10. await input.type("大闹天宫");
  11. await page.keyboard.press('Enter');
  12. await page.waitForSelector(".search_list>.song_item")
  13. const list = await page.$$eval(".search_list>.song_item",ele=>{
  14. return ele.length;
  15. })
  16. console.log(list)
  17. })()