# 自动化任务

# 网页截图

node.js + selenium

const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const {By, until} = require('selenium-webdriver');
const options = new chrome.Options();
options.addArguments('--headless');
const driver = new webdriver.Builder()
        .forBrowser('chrome')
        .setChromeOptions(options)
        .build();

const url = 'http://www.example.com'
const tokenValue = 'WY1ksZ9wUbyTua5Cij2GJDIPMXRKLq6N'
const urlWithToken = url + '?user-token=' + encodeURICompoent(tokenValue);

async function captureScreenshot() {
    try {
        // await driver.get(url);
        // await driver.manage().addCookie({name:'user-token', value: tokenValue})
        // await driver.get(url);
        await driver.get(urlWithToken);
        // 等待页面加载完成
        await driver.wait(until.elementLocated(By.css('#page-anchor .is-loaded')), 60 * 1000);
        // 调整窗口高度,完成长截图
        const anchorEl = driver.findElement(By.css('#page-anchor'))
        const anchorRect = anchorEl.getRect()
        const pageHeight = anchorRect.y || 4096;
        await driver.manage().window().setSize({width: 1920, height: pageHeight})
        // 截图
        const data = await driver.takeScreenshot();
        // 写入文件或上传
        require('fs').writeFileSync('example.png', data, 'base64');
        await driver.quit();
    } finally {
        await driver.quit();
    }
}
captureScreenshot();

node.js + puppeteer

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({headless: true});
    const page = await browser.newPage();
    await page.goto('http://www.example.com');
    await page.waitForSelector('div#example');
    await page.screenshot({path: 'example.png'});
    await browser.close();
})();

java + selenium

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Example {
  public static void main(String[] args) throws IOException {
    ChromeOptions options = new ChromeOptions();
    options.setHeadless(true);
    WebDriver driver = new ChromeDriver(options);
    driver.get("http://www.example.com");
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div#example")));
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File("example.png"));
    driver.quit();
  }
}

# 批量登录

// 表单点击登录
async function loginByForm(page, user){
  await page.type("[type=text]", user.username);
  await page.type("[type=password]", user.password); 
  await page.click(".login-btn");
}
// Http Basic 登录
async function loginByBasic(page, user){
  await page.authenticate({
    username: user.username,
    password: user.password,
  });
}    
function craeteLoginTask(browser, user, url) {
    return function task() {
      return new Promise(async (resolve, reject) => {
        const page = await browser.newPage({ waitUntil: ["load"] });
        await page.goto(url);
        await loginByForm(page, user);
        // await loginByBasic(page, user);
        await page.waitForNavigation(); // 页面登录成功后,需要保证redirect 跳转到请求的页面
        resolve();
      });
    };
  }
const puppeteer = require("puppeteer");
const webpageUrl = "https://192.168.0.1/";
const userlist = [
  {
    username: "admin",
    password: "admin"
  }
];

// launch browser
const browser = await puppeteer.launch({
  headless: false,
  defaultViewport: { width: 1920, height: 1080 },
  args: ["--ignore-certificate-errors", "--use-fake-ui-for-media-stream"]
});

async function batchLogin(userlist) {
  const taskList = [];
  userlist.forEach((user) => {
    const task = craeteLoginTask(browser, user, webpageUrl)
    taskList.push(task);
  });
  serialExecute(taskList);
}

batchLogin(userlist);