selenium 动态填充表单, 模拟鼠标右键保存图片

1. 下载驱动,解压驱动(测试环境ubuntu 18.04)

http://npm.taobao.org/mirrors/chromedriver/

 

2. 代码

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import java.awt.*;
import java.awt.event.KeyEvent;

public class Selenium2Example  {
    public static void main(String[] args) throws Exception{
        System.setProperty("webdriver.chrome.driver", "/project/122/chromedriver");
        ChromeOptions options = new ChromeOptions();
        // options.setHeadless(true);
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("http://bj.122.gov.cn/");
        Thread.sleep(500);
        System.out.println("打开浏览器");

        driver.findElement(By.id("WFhpzl")).sendKeys("使馆汽车");
        driver.findElement(By.id("hphm1-b")).sendKeys("666677");
        driver.findElement(By.id("WFfdjh")).sendKeys("55555");

        // 触发验证码焦点,获取验证码
        Actions actions = new Actions(driver);
        Robot robot = new Robot();
        robot.setAutoDelay(100);
        WebElement yzm =  driver.findElement(By.name("captcha"));
        actions.contextClick(yzm).perform();
        Thread.sleep(50);
        robot.keyPress(KeyEvent.VK_ESCAPE);
        Thread.sleep(50);
        robot.keyRelease(KeyEvent.VK_ESCAPE);
        Thread.sleep(2000);

        // 下载图片
        try{
            WebElement yzmtp = driver.findElement(By.xpath("//*[@id=\"WFForm\"]/div[4]/span/img"));
            System.out.println("ok");
            // 保存图片
            actions.moveToElement(yzmtp).contextClick().perform();
            // 保存
            robot.keyPress(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_V);
            // 确认
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
            // 文件名字后确认
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
            System.out.println("save ok");

        }catch (NoSuchElementException e){
            System.out.println("not ok");
        }
        System.out.println("title is: " + driver.getTitle());
    }
}

mvn:


   org.seleniumhq.selenium
   selenium-server
   3.141.59

3. 可以借助tess4j识别下载的验证码,  悲剧的是验证码的识别率太低..........

 

你可能感兴趣的:(爬虫,练习)