如何使用 Selenium 获取浏览器中的页面源代码?

seleniumautomation testingtesting tools

我们可以使用 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();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get ("https://www.tutorialspoint.com/about/about_careers.htm");
      //获取页面源代码
      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();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //使用 getText 方法获取页面源代码
      WebElement l= driver.findElement(By.tagName("body"));
      String p = l.getText();
      System.out.println("Page Source is : " + p);
      driver.close();
   }
}

相关文章