如何使用 Selenium 从网页中提取文本并将其保存为文本文件?

seleniumautomation testingtesting tools

我们可以使用 Selenium webdriver 从网页中提取文本,并使用 getText 方法将其保存为文本文件。它可以提取显示元素(未被 CSS 隐藏)的文本。

我们必须使用任意定位器(例如 id、class、name、xpath、css、标签名称、链接文本或部分链接文本)在页面上定位元素。获取文本后,我们将借助 File 类将其内容写入文件。

让我们获取文本——您正在浏览以下页面,这是在线教育的最佳资源 −

示例

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;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import java.nio.charset.Charset;
public class GetTxtSaveFile{
   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/index.htm");
      // 识别元素
      WebElement e = driver.findElement(By.tagName("h4"));
      // 获取文本
      String s = e.getText();
      // 将文本写入文件

      File f = new File("savetxt.txt");
      try{
         FileUtils.writeStringToFile(f, s, Charset.defaultCharset());
      }catch(IOException exc){
         exc.printStackTrace();
      }
      driver.quit();
   }
}

输出

项目内会生成 savetxt.txt 文件,用于捕获页面中的文本。


相关文章