playwright节点截图demo

const { chromium,firefox } = require('playwright');
const fs = require('fs');
const path = require('path');
const axios = require('axios');

(async () => {
//使用现有浏览器的配置
//谷歌浏览器用户数据
  // const userDataDir = "C:\\Users\\xxx\\AppData\\Local\\Google\\Chrome\\User Data"; // 
 //火狐浏览器用户数据
const userDataDir = "C:\\Users\\xxx\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\c2ifnqb7.default-release"; 

//使用浏览器时,需要先关闭浏览器,否则代码无法正常运行
  const browser = await firefox.launchPersistentContext(userDataDir, {
    headless: false, // 设置为false来打开浏览器界面
    // args: ['--disable-extensions']  
  });
  // const browser = await chromium.launch({ headless: false });

  // 启动浏览器
  // 新建页面
  const page = await browser.newPage();
  // 访问指定网址
  await page.goto('https://www.xxx.app/read/13809/3', { timeout: 60000 });
  //等待对应标签加载完成后再操作
  await page.waitForSelector('.main', { timeout: 50000 });
  await page.waitForSelector('.illus', { timeout: 50000 });
  // 删除干扰标签
  await page.evaluate(() => {
    const header = document.querySelector('header');
    const aside = document.querySelector('aside');
    const img = document.querySelector('.illus.duokan-image-single img');
    console.log("图片", img);
    const notify = document.querySelector('#q-notify');
    const loading = document.querySelector('#q-loading-bar');
    if (header) {
      header.remove(); // 删除 header 节点
    }
    if (aside) {
      aside.remove(); // 删除 header 节点
    }
    if (img) {
      console.log('删除图片');
      // img.remove()
      img.style.display = 'none'; // 删除 header 节点
    } else {
      console.log('Element not found');
    }
    if (notify) {
      notify.remove();
    }
    if (loading) {
      loading.remove();
    }

  });
  // 隐藏所有 fixed 定位的元素(节点截图会把fixed定位元素也算在内)
  await page.evaluate(() => {
    const fixedElements = document.querySelectorAll('*');
    fixedElements.forEach(el => {
      const style = window.getComputedStyle(el);
      if (style.position === 'fixed') {
        el.style.display = 'none'; // 隐藏 fixed 定位的元素
      }
    });
  });

  //拿到节点
  const mainElement = await page.$('.main');
  
  
  //截图
  await mainElement.screenshot({ path: 'example.png' });
  // 关闭浏览器
  await browser.close();
})();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值