Last active
July 8, 2018 11:52
-
-
Save tdaniely/a917d5839106a5fd851d4389899cb472 to your computer and use it in GitHub Desktop.
Interweave cdp4j with selenium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonParser; | |
import io.webfolder.cdp.session.SessionFactory; | |
import org.openqa.selenium.HasCapabilities; | |
import org.openqa.selenium.Keys; | |
import org.openqa.selenium.WebDriver; | |
import org.openqa.selenium.chrome.ChromeDriver; | |
import org.openqa.selenium.chrome.ChromeDriverService; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.net.URL; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.Map; | |
public class Main { | |
public static void main(String[] args) { | |
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, "C:\\path\\to\\chromedriver.exe"); | |
var driver = new ChromeDriver(); | |
try { | |
var cdp = findCdpEndpoint(driver); | |
System.out.println(cdp.toString()); | |
try (var factory = new SessionFactory(cdp.getPort())) { | |
driver.navigate().to("https://google.com"); | |
String seTargetId = getSeTargetId(cdp, driver.getTitle()); | |
try (var session = factory.connect(seTargetId)) { | |
session.waitDocumentReady(); | |
session.sendKeys("Astronauts"); | |
driver.getKeyboard().sendKeys(Keys.RETURN); | |
session.wait(2000); | |
driver.navigate().to("http://www.google.com"); | |
session.waitDocumentReady(); | |
} | |
} | |
} catch (Exception ex) { | |
System.out.println(ex.toString()); | |
} | |
driver.quit(); | |
} | |
private static String getSeTargetId(URL cdp, String title) throws IOException { | |
for (JsonElement element : new JsonParser().parse(new InputStreamReader(cdp.openStream(), "UTF-8")).getAsJsonArray()) { | |
var object = element.getAsJsonObject(); | |
if (title == null || title.isEmpty() | |
? object.get("type").getAsString().equalsIgnoreCase("page") | |
: object.get("title").getAsString().equalsIgnoreCase(title)) { | |
return object.get("id").getAsString(); | |
} | |
} | |
throw new IllegalStateException("Selenium target not found."); | |
} | |
private static URL findCdpEndpoint(WebDriver driver) throws IOException { | |
var capChrome = (Map<?,?>) ((HasCapabilities)driver).getCapabilities().getCapability("chrome"); | |
var userDataDir = (String) capChrome.get("userDataDir"); | |
var port = Integer.parseInt(Files.readAllLines(Paths.get(userDataDir, "DevToolsActivePort")).get(0)); | |
return new URL("http", "localhost", port, "/json"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment