How to get Json response by selenium webdriver using Java?

那年仲夏 提交于 2021-02-11 13:57:01

问题


I'm trying to get Json response by selenium webdriver. How to get it as a Json format. Currently what I get is a String format.

Here is what I'm trying to get: {"id":377,"text":"Playing Sudoku is fun!"}

<pre style="word-wrap: break-word; white-space: pre-wrap;">{"id":377,"text":"Playing Sudoku is fun!"}</pre>

Here is my code:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class GameTestSelenuim {

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","/Users/lulu/Desktop/Selenium/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.get("http://localhost:8080/game");
    driver.manage().window().maximize();
    String text = driver.findElement(By.cssSelector("pre")).getText();
    System.out.println(text);
}

}


回答1:


Selenium getText() method always returns a string value. You can convert the json string value to JSON object using any JSON library.

Here I used org.json library.

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","/Users/lulu/Desktop/Selenium/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.get("http://localhost:8080/game");
    driver.manage().window().maximize();
    String text = driver.findElement(By.cssSelector("pre")).getText();
    System.out.println(text);
    JSONObject jsonobject = new JSONObject(text);
    System.out.println(jsonobject.getString("text"));
    System.out.println(jsonobject.getInt("id"));
}

JSONObject jsonobject = new JSONObject(text) - Here we create JSON object.



来源:https://stackoverflow.com/questions/54270471/how-to-get-json-response-by-selenium-webdriver-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!