1. const puppeteer = require("puppeteer");
  2. const url = "https://music.163.com/";
  3. const cheerio = require("cheerio")
  4. async function show () {
  5. const browser = await puppeteer.launch({
  6. defaultViewport: null, //可视区域最大化
  7. });
  8. const page = await browser.newPage();
  9. await page.goto(url)
  10. await page.waitForSelector("iframe");
  11. const elementHandle = await page.$('iframe');
  12. const frame = await elementHandle.contentFrame();
  13. const content = await frame.content(frame);
  14. const $ = cheerio.load(content,{
  15. decodeEntities:false
  16. })
  17. var items = $(".n-rcmd ul.f-cb li")
  18. var arr = [];
  19. items.each((index,ele)=>{
  20. var title = $(ele).find(".dec a").html()
  21. var img = $(ele).find(".u-cover img").attr("src")
  22. arr.push({
  23. title,
  24. img
  25. })
  26. })
  27. console.log(arr)
  28. }
  29. show()
  1. # .contentFrame() 获取iframe中的html结构。
  2. const elementHandle = await page.$('iframe');
  3. const frame = await elementHandle.contentFrame();

1-1 在iframe的input框中输入

  1. const puppeteer = require("puppeteer");
  2. const url = "https://login.anjuke.com/login/form";
  3. const cheerio = require("cheerio")
  4. async function show () {
  5. const browser = await puppeteer.launch({
  6. headless:false,
  7. defaultViewport: null, //可视区域最大化
  8. });
  9. const page = await browser.newPage();
  10. await page.goto(url)
  11. await page.waitForSelector("#iframeLoginIfm");
  12. const elementHandle = await page.$('#iframeLoginIfm');
  13. const frame = await elementHandle.contentFrame();
  14. const tel = await frame.$("#phoneIpt");
  15. await tel.type("189")
  16. }
  17. show()

1-2 frames().find()获取iframe

  1. const puppeteer = require("puppeteer");
  2. const url = "https://login.anjuke.com/login/form";
  3. async function show () {
  4. const browser = await puppeteer.launch({
  5. headless:false,
  6. defaultViewport: null, //可视区域最大化
  7. });
  8. const page = await browser.newPage();
  9. await page.goto(url)
  10. /* 切换iframe */
  11. var target = "https://login.anjuke.com/login/iframeform"
  12. const frame = await page.frames().find(frame=>frame.url().includes(target));
  13. var input = await frame.$("#phoneIpt");
  14. await input.type("189")
  15. }
  16. show()