如何在使用硒单击按钮后获取页面源

How to get page source after button click using selenium

我试图在单击搜索按钮后获取页面源代码。这是我的代码:

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

并且此代码returns第一页的页面源,而不是点击后加载的那个...

您需要在获取页面源之前明确等待新页面加载。这通常取决于您正在使用的网页。例如,您可以等到特定元素变得可见:

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

driver.getPageSource();

实际上你不应该依赖那个方法,因为不能保证它代表你的当前状态,实现也取决于你使用的特定驱动程序。

来自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