如何使用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