0


使用node调用chrome(基于selenium-webdriver包)

下载测试版chrome和chromedriver

https://googlechromelabs.github.io/chrome-for-testing/

把chromedriver复制到chrome的文件里

设置环境变量

编写代码

const { Builder, Browser, By, Key, until } = require('selenium-webdriver')
const puppeteer = require('puppeteer')

//查询
const chromiumSearch = async (req, res) => {
  const { type = '' } = req.body

  if (type === 'puppeteer') {
    async function pageScreenshot(url, path = 'screenshot.png') {
      const browser = await puppeteer.launch()
      const page = await browser.newPage()
      await page.goto(url)
      await page.screenshot({ path })
      await browser.close()
    }

    // 使用函数将指定网页转换为图片
    pageScreenshot('https://www.baidu.com', '/temp/ai/puppeter/example.png')

    res.send({
      code: 200,
      data: {},
      message: '成功',
    })
  } else if (type === 'selenium-webdriver') {
    let driver = await new Builder().forBrowser(Browser.CHROME).build()

    try {
      //await driver.get('https://www.baidu.com')
      await driver.get('http://localhost:85/test1.html')

      // await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN)
      // await driver.wait(until.titleIs('webdriver - Google Search'), 3000)
      // await driver.wait(until.titleIs('webdriver - Google Search'), 1000)

    // 等待页面加载完成
    // await driver.wait(until.titleIs('Example Domain'), 10000);
 
    // 滚动到页面顶部
    await driver.executeScript('window.scrollTo(0, 0);');
 
    // 等待一会,确保页面加载和渲染完成
    await new Promise(resolve => setTimeout(resolve, 3000));
 
    // 获取页面截图并保存为图片
    const screenshot = await driver.takeScreenshot();
    const base64Data = screenshot.replace(/^data:image\/png;base64,/, '');
    const fs = require('fs');
    let now = Date.now()
    fs.writeFileSync(`/temp/ai/chromium/${now}.png`, base64Data, 'base64');
 
    console.log('网页已转换成图片: screenshot.png');

    } finally {
      await driver.quit()
    }

    res.send({
      code: 200,
      data: {},
      message: '成功',
    })
  } else {
    res.send({
      code: 400,
      data: {},
      message: '参数错误:type',
    })
  }
}

module.exports = {
  chromiumSearch,
}

参考链接:

https://blog.csdn.net/qq_52867389/article/details/132197894

人工智能学习网站

https://chat.xutongbao.top

标签: chrome 前端

本文转载自: https://blog.csdn.net/xutongbao/article/details/138306519
版权归原作者 徐同保 所有, 如有侵权,请联系我们删除。

“使用node调用chrome(基于selenium-webdriver包)”的评论:

还没有评论