//jsoup获取cookies
private static Integer TIMEOUT = 10000;
private static String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36";
private static String URL="http://www.***.com/loginnew.asp";
public static Map getLoginCookeis(){
try {
//登陆时发送的数据,
Map map = new HashMap();
map.put("username", "用户名");
map.put("password", "密码");
map.put("Action", "Login");
map.put("Submit.x", "40");
map.put("Submit.y", "15");
Map map1 = new HashMap();
map1.put("ASPSESSIONIDASBTBDDT", "ACABMBFDKBGHOLHBHMKKMHLA");
map1.put("Sailing", "Skin=");
//发送请求
Connection.Response rs=Jsoup.connect(URL)
.postDataCharset("GB2312")//编码
.data(map)//请求参数
.userAgent(USER_AGENT)
.cookies(map1)//cookies
.timeout(TIMEOUT)//超时
.method(Connection.Method.POST)
.execute();
map1=rs.cookies();//获取登录的cookies
return map1;
} catch (IOException ex) {
Logger.getLogger(KechengbiaoLogin.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
//selenium登陆
public static void getIndex() {
try {
//下载chromedriver.exe保存,使用chrome浏览器
System.getProperties().setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
webDriver.get("http://www.****.com/loginnew.asp"); webDriver.manage().deleteAllCookies();//需先打开登录页面,然后将jsoup获取到的登录后的cookies放入页面
Map cookies = KechengbiaoLogin.getLoginCookeis(); for (Object entry : cookies.keySet()) { Cookie cookie = new Cookie(entry + "", cookies.get(entry) + ""); webDriver.manage().addCookie(cookie); }
webDriver.get("http://www.****.com/Index.asp");//登录后的页面
//左侧栏目菜单 webDriver.switchTo().frame("left");//进入左侧frame,如果页面上有多个frame页面嵌套,这里就需要
//点开所有菜单 List<WebElement> tbs = webDriver.findElements(By.xpath("//body/table")); for (WebElement we : tbs) { we.click(); }
List<WebElement> links = webDriver.findElements(By.tagName("a"));//获取左侧菜单所有链接
webDriver.switchTo().defaultContent();//webDriver退到整个窗口,然后才能调转到别的frame里面去
webDriver.switchTo().frame("frameName");
} catch (InterruptedException ex) { Logger.getLogger(kechengbiaoIndex.class.getName()).log(Level.SEVERE, null, ex); }finally{ webDriver.close();//运行完需要关闭chrome driver,否则你的进程会无限增加 } }