selenium 隐藏浏览器+截图

时间:2024-02-18 10:49:12

python代码如下

from selenium import webdriver
#隐藏浏览器
chrome_opts=webdriver.ChromeOptions()
chrome_opts.add_argument("--headless")
#Chromedriver存放路径
path=\'C:\\Users\\yjh\\Downloads\\chromedriver_win32\\chromedriver.exe\'
driver=webdriver.Chrome(path,chrome_options=chrome_opts)
try:
    driver.get("http://www.baidu.com")
    driver.find_element_by_id(\'kw\').send_keys(\'12306\')
    #截图
    driver.get_screenshot_as_file("D:\\baidu12306.png")
except RuntimeError as error:
    print(error)
finally:
    driver.quit()

 java代码如下,需要添加依赖

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

 

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
import java.io.IOException;

public class ScreenShot {
    public static void main(String[] args) {
        //设置启动路径
        System.setProperty("webdriver.chrome.driver","C:\\Users\\yjh\\Downloads\\chromedriver_win32\\chromedriver.exe");
        //隐藏浏览器
        ChromeOptions options=new ChromeOptions();
        options.addArguments("--headless");

        WebDriver driver=new ChromeDriver(options);
        driver.get("url");
        //截图
        File scr=((ChromeDriver) driver).getScreenshotAs(OutputType.FILE);
        try {
            //拷问截图文件
            FileUtils.copyFile(scr,new File("D:\\screenShot.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        driver.quit();
    }
}