如何在 Selenium 中获取图片的 src 属性?

seleniumautomation testingtesting tools更新于 2026/2/12 10:52:17

我们可以在 Selenium 中获取图片的来源。HTML 文档中的图片具有 <img> 标签名。每张图片还具有一个属性 src,该属性包含图片在页面中的来源。

要在 Selenium 中获取任何属性,我们必须使用 getAttribute() 方法。该方法将属性名称作为参数。因此,要获取 src 属性,我们必须编写 getAttribute("src")。

示例

代码实现。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Imagesrc{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // 识别图像
      WebElement l =driver.findElement(By.xpath("//img[@title='Tutorialspoint']"));
      //getAttribute() 获取图像的 src
      System.out.println("Src attribute is: "+ l.getAttribute("src"));
      driver.quit();
   }
}

输出


相关文章