在使用selenium + java时,在Chrome Headless模式下未启用地理位置,但是在没有headless模式下可以完美地工作

时间:2019-02-01 20:06:27

标签: java selenium google-chrome-headless

我有我从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无头模式下启用地理位置

1 个答案:

答案 0 :(得分:0)

尝试一下。看看是否可行。

 WebElement element = driver.findElement(By.xpath("//p[@id='demo']"));
 String html = element.getAttribute("innerHTML");
 System.out.println(html);