如何使用selenium从任何站点获取页面内容?
这是我的代码,它返回空值,但在浏览器控制台中运行良好如何使用selenium从任何站点获取页面内容?,selenium,Selenium,这是我的代码,它返回空值,但在浏览器控制台中运行良好 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
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();
}
}
此代码获取页面的内容(不是源代码),将其存储在变量content中,然后在控制台中打印
如果您想获取页面的源代码,您应该使用
webDriver.getPageSource()
方法。对不起,但不太清楚为什么要获取页面的源代码。此外,WebDriver旨在通过UI执行测试。为了只操作HTTP请求/响应,有更合适的库。
WebDriver webDriver = new FirefoxDriver();
webDriver.get("https://in.yahoo.com/");
String content = webDriver.findElement(By.tagName("body")).getText();
System.out.println(content);