我有我从W3Schools获得的html
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
我已经在没有无头模式的情况下使用了这样的硒代码,
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("file:///C:/Users/user/Desktop/test.html");
driver.findElement(By.tagName("button")).click();
Thread.sleep(4000);
System.out.println("*******************************");
System.out.println(driver.findElement(By.id("demo")).getText());
System.out.println("*******************************");
}
,输出为:
'*******************************
Latitude: 13.009112499999999
Longitude: 77.7006038
'*******************************
但是当我以 headless 模式运行时,
public static void main(String[] args) throws InterruptedException {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("headless");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("file:///C:/Users/user/Desktop/test.html");
driver.findElement(By.tagName("button")).click();
Thread.sleep(4000);
System.out.println("*******************************");
System.out.println(driver.findElement(By.id("demo")).getText());
System.out.println("*******************************");
}
输出为:
'********************************
'*******************************
我想念什么? 我只能使用无头,并且无法在Chrome无头模式下启用地理位置。
答案 0 :(得分:0)
尝试一下。看看是否可行。
WebElement element = driver.findElement(By.xpath("//p[@id='demo']"));
String html = element.getAttribute("innerHTML");
System.out.println(html);