简体   繁体   中英

Making Webpage headless is causing issue with finding WebElement through Xpath

I had to make chrome browser headless after which when I try to see the html code by executing below lines

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ldriver = new ChromeDriver(options);
String stored_Text = ldriver.getPageSource();
System.out.println(stored_Text);

Output is:

<html><head></head><body></body></html>

Because of which when I write xpath after making the page headless I'm getting no such element exception

Is there a way for me to circumvent this problem. Please help

Before invoking getPageSource() ideally you need to induce WebDriverWait for the visibilityOfElementLocated() for any of the static and visible element on the page.


An example

As an example to extract the page_source of Google Home Page you need to wait for the Search Box to be visible as follows:

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ldriver = new ChromeDriver(options);
ldriver.get("https://www.google.com/");
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.name("q")));
String stored_Text = ldriver.getPageSource();
System.out.println(stored_Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM