Java使用WebDriver模拟登陆(Chrome)

打开一个浏览器窗口

    WebDriver driver = new ChromeDriver();

打开要登陆的网站(GitHub登陆页面)

    driver.get("https://github.com/login");

获取用户名、密码框并设置值

    WebElement elemUsername = driver.findElement(By.id("login_field"));    //获取用户名框

    WebElement elemPassword = driver.findElement(By.id("password"));    //获取密码框

    WebElement btn = driver.findElement(By.cssSelector("input[class='btn btn-primary btn-block']"));    //获取点击登陆按钮。

注:也可以用By.className("");

    如果定位class是含有空格的复合类,用By.cssSelector可以解决;

    elemUsername.sendKeys("***");    

    elemPassword.sendKeys("***");    

    btn.submit();    // 点击行为

 

代码如下:

String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "browserDriver/chromedriver_x64.exe";
	  	File file = new File(filePath);
	  	if (!file.exists())
	  	{
	  	  filePath = "browserDriver/chromedriver_x64.exe";
	  	}
	  	System.setProperty("webdriver.chrome.driver", filePath);
	  	WebDriver driver = new ChromeDriver();
	  	
	  	driver.get("https://github.com/login");
WebElement elemUsername = driver.findElement(By.id("login_field"));
WebElement elemPassword = driver.findElement(By.id("password"));
        WebElement btn = driver.findElement(By.cssSelector("input[class='btn btn-primary btn-block']"));
elemUsername.sendKeys("***");
elemPassword.sendKeys("***");
	  	btn.submit();

 

 

 

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