如何使用Selenium 获取整个页面的内容?
我们可以使用Selenium获取整个页面的内容。有不止一种方法可以实现。要获得页面上可见的文本,我们可以使用findElement(By.tagname()) 方法进行获取。接下来可以使用getText() 方法从body标签中提取文本。
语法 −
WebElement l=driver.findElement(By.tagName("body"));
String t = l.getText();获取整个页面内容的另一种方法是使用getPageSource() 方法。
语法 −
String l = driver.getPageSource();
示例
使用 <body> 标签的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextContent{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com/";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element and input text inside it
WebElement l =driver.findElement(By.tagName("body"));
System.out.println("Text content: "+ l.getText());
driver.quit();
}
}输出

示例
使用 getPageSource() 的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageSrc{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com/";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// getPageSource() and print
String l = driver.getPageSource();
System.out.println("Page source: "+ l);
driver.quit();
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP