如何使用 Selenium 獲取瀏覽器中的頁面原始碼?
使用 Selenium WebDriver 我們可以透過 getPageSource 方法獲取與瀏覽器中相同的頁面原始碼。這允許我們獲取頁面原始碼。
語法
String p = driver.getPageSource();
我們還可以透過使用 findElement 方法識別 body 標籤,然後對其使用 getText 方法來獲取頁面原始碼。將引數 By.tagName 作為引數傳遞給 findElement 方法。
語法
WebElement l= driver.findElement(By.tagName("body"));
String p = l.getText();示例
使用 getPageSource 的程式碼實現
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PgSrc{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get ("https://tutorialspoint.tw/about/about_careers.htm");
//get page source
String p = driver.getPageSource();
System.out.println("Page Source is : " + p);
driver.close();
}
}使用 body 標籤名的程式碼實現
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PgSrcBody{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.tw/about/about_careers.htm");
//get page source with getText method
WebElement l= driver.findElement(By.tagName("body"));
String p = l.getText();
System.out.println("Page Source is : " + p);
driver.close();
}
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
JavaScript
PHP