需求:
如何在新启动的应用, 使用上一次应用打开的那个浏览器?
由于每次启动应用, 都会全新打开一个新的浏览器, 在一个新的会话下进行工作.
Solution:
由于之前使用的是Session来进行通信的, 那么可以使用上一次会话的sessionid
具体解决方案:
- 使用RemoteWebDriver的方式进行创建Selenium服务.
- 将chromedriver.exe 和 selenium-server-standalone-3.3.1.jar 放在同一个文件夹内
- 使用 java -jar selenium-server-standalone-3.3.1.jar 命令启动Selenium服务.
- 打开http://localhost:4444/wd/hub/static/resource/hub.html 查看,如果是下面的界面, 则表示Selenium服务启动成功.
2. 创建RemoteWebDriver的实现类,
- 由于RemoteWebDriver类中的setSessionID是Protected的, 无法直接调用, 所以创建子类进行扩展.
- 创建子类 MyWebDriver, 并将setSessionId置为 public
public class MyWebDriver extends RemoteWebDriver {
public MyWebDriver(URL url, DesiredCapabilities cap) {
super(url, cap);
}
@Override
public void setSessionId(String opaqueKey) {
super.setSessionId(opaqueKey);
}
}
-
使用的时候, 使用之前的那个sessionid进行使用, 例如 访问Baidu.
@Test
public void usingOpenedPageForAccessBaidu() throws MalformedURLException {
String sessinId = "b0c01669-624f-4b9f-9ed4-e8419492f1891";
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setPlatform(Platform.ANY);
String urlStr = "http://localhost:4444/wd/hub";
RemoteWebDriver driver=new RemoteWebDriver(new URL(urlStr),cap);
MyWebDriver driver = new MyWebDriver(new URL(urlStr), cap);
String newSessionId = driver.getSessionId().toString();
try {
driver.setSessionId(sessinId);
String url = driver.getCurrentUrl();
driver.get("http://www.baidu.com");
driver.findElement(By.cssSelector("#kw")).sendKeys("hello");
driver.findElement(By.cssSelector("#su")).click();
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.setSessionId(newSessionId);
driver.quit();
}
}
- 例子2, 关闭所有已经打开的Session
@Test
public void getAllSessionAndCloseIt() throws MalformedURLException {
List<String> sessionList = new ArrayList<>();
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setPlatform(Platform.ANY);
String urlStr = "http://localhost:4444/wd/hub";
MyWebDriver driver = new MyWebDriver(new URL(urlStr), cap);
driver.get("http://localhost:4444/wd/hub/static/resource/hub.html");
List<WebElement> eles = driver.findElements(By.cssSelector(".session-container>.control-block>button"));
WebElement refreshBtnEle = eles.get(1); //Click the refeash button
refreshBtnEle.click();
List<WebElement> tbsEles = driver.findElements(By.cssSelector(".goog-tab"));
for (WebElement tbsEle : tbsEles) {
tbsEle.click();
WebElement sessionLabel = driver.findElements(By.cssSelector(".control-block span")).get(0);
String session = sessionLabel.getText();
System.out.println("session----->:" + session);
sessionList.add(session);
}
for (String session : sessionList) {
driver.setSessionId(session);
driver.quit();
}
}