问题
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