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