Dmitrij Kultasev
Dmitrij Kultasev

Reputation: 5745

How to get page source after button click using selenium

I am trying to get page source after clicking on search button. This is my code:

WebDriver driver = new ChromeDriver();
driver.get(page);
WebElement el = driver.findElement(By.xpath(xpath)); // button
el.click();
driver.getPageSource();

and this code returns the page source of the first page, not the one that was loaded after the click ...

Upvotes: 2

Views: 7078

Answers (2)

Erki M.
Erki M.

Reputation: 5072

Actually you shouldn't rely on that method as there is no guarantee that it represents your current state, the implementation also depends on the particular driver that you are using.

From the docs:

java.lang.String getPageSource()

Get the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page. Please consult the documentation of the particular driver being used to determine whether the returned text reflects the current state of the page or the text last sent by the web server. The page source returned is a representation of the underlying DOM: do not expect it to be formatted or escaped in the same way as the response sent from the web server. Think of it as an artist's impression.

Returns: The source of the current page

Upvotes: 1

alecxe
alecxe

Reputation: 473873

You need to explicitly wait for the new page to load before getting the page source. This usually depends on the webpage you are working with. For instance, you may wait until a particular element becomes visible:

WebDriverWait wait = new WebDriverWait(webDriver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("myid")));

driver.getPageSource();

Upvotes: 4

Related Questions