点击Selenium Webdriver中的图片

访问图片链接

图片链接是指网页中由图片表示的链接,点击后会跳转到不同的窗口或页面。

由于它们是图片,我们不能使用 By.linkText() 和 By.partialLinkText() 方法,因为图片链接基本上没有任何链接文本。

在这种情况下,我们应该使用 By.cssSelector 或 By.xpath。第一种方法因其简洁性而更受欢迎。

在下面的示例中,我们将访问 Facebook 密码找回页面左上角的“Facebook”标志。

Accessing Image Links

我们将使用 By.cssSelector 和元素的“title”属性来访问图片链接。然后我们将验证我们是否跳转到了 Facebook 主页。

package newproject;
import org.openqa.selenium.By;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.chrome.ChromeDriver;		

public class MyClass {				
    		
    public static void main(String[] args) {									
        String baseUrl = "https://#/login/identify?ctx=recover";					
        System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");					
        WebDriver driver = new ChromeDriver();					
        		
        driver.get(baseUrl);					
        //click on the "Facebook" logo on the upper left portion		
			driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click();					

			//verify that we are now back on Facebook's homepage		
			if (driver.getTitle().equals("Facebook - log in or sign up")) {							
            System.out.println("We are back at Facebook's homepage");					
        } else {			
            System.out.println("We are NOT in Facebook's homepage");					
        }		
				driver.close();		

    }		
}

结果

Click on Image in Selenium Webdriver

结论

这就是点击图片的全部内容。访问图片链接使用 By.cssSelector() 完成。