如何使用 Selenium 获取网站文本?
seleniumautomation testingtesting tools
我们可以使用 Selenium WebDriver 的 getText 方法获取网站文本。该方法有助于获取特定元素的可见文本或内部文本(即页面中未隐藏的文本)。
首先,我们必须借助定位器(例如 id、class、name、xpath、css、标签名称、链接文本或部分链接文本)来识别页面上需要获取文本的元素。
让我们尝试检索文本 - 以实惠的价格享受优质内容,请访问以下页面 −

语法
WebElement n =driver.findElement(By.tagName("h2"));
String s = n.getText();
示例
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 ElementTxt{
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 s = driver.findElement(By.tagName("h2"));
// 获取元素文本
String st = s.getText();
System.out.println("Text is : " + st);
driver.quit();
}
}
输出


