如何使用 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();
   }
}

更新於: 2021-04-06

11K+ 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

入門
廣告
© . All rights reserved.