这是我的代码,它返回空值但在浏览器控制台中运行良好
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class google {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("https://in.yahoo.com/");
JavascriptExecutor js;
js = (JavascriptExecutor)driver;
String scriptReturningString = "";
String scriptResult = (String)js.executeScript("return document.getElementsByTagName('body')[0].innerText");
System.out.println("Text Inside:"+scriptResult);
driver.quit();
}
}
最佳答案
WebDriver webDriver = new FirefoxDriver();
webDriver.get("https://in.yahoo.com/");
String content = webDriver.findElement(By.tagName("body")).getText();
System.out.println(content);
此代码获取页面的内容(不是源代码),将其存储在变量 content 中,然后在控制台中打印。
如果你想获取页面的源代码,你应该使用 webDriver.getPageSource()
方法。
关于selenium - 如何使用 Selenium 从任何网站获取页面内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23536385/