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.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/

相关文章:

javascript - driver.getTitle() 从错误页面获取数据

java - DOM 中不再存在移动元素 - selenium

python - 使用 Selenium 获取两个标签之间的 HTML

python - selenium.common.exceptions.WebDriverException : Message: unknown error: Failed to create Chrome process with ChromeDriver Chrome with Selenium Python

python - Selenium:检索向下滚动时加载的数据

python - 如何在 Windows 10 上安装 ChromeDriver 并使用 Chrome 运行 Selenium 测试?

python - 使用 python 进行 Selenium 网络抓取 - 任何没有名字的下拉菜单

java - 如何在 catch block 中打印变量?

javascript - 如何在 JMeter 的 Webdriver Sampler 中获取警报消息?

python - 获取 DOM 树中元素的 XPath?