文章首发于微信公众号:软测小生
访问图片链接
图像链接是Web页面中由图像表示的链接,当点击该图片(链接)时,将导航到另一个窗口或页面。
因为它们是图像,所以我们不能使用**By.linkText()和By.partialLinkText()**方法,因为图像链接基本上没有链接文本。
在这种情况下,我们应该使用任意一种方法:cssSelector或By.xpath,第一种方法更受欢迎,因为它简单。
在下面的示例中,我们将访问Baidu主页上的Baidu徽标。
我们将使用By.cssSelector和元素的“title”属性来访问图像链接。然后我们将验证点击之后是否会跳转到对应的页面上。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class testSelenium {
public WebDriver driver;
@BeforeMethod()
public void beforeTest() {
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
options.setExperimentalOption("prefs", prefs);
System.setProperty("webdriver.chrome.driver", "Driver/chromedriver.exe");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}
@Test()
public void testBaidu() {
String url = "https://www.baidu.com/s?&wd=%E7%99%BE%E5%BA%A6";
driver.get(url);
WebElement baiduImg;
baiduImg = driver.findElement(By.xpath("img[title='到百度首页']:nth-child(1)"));
baiduImg.click();
if(driver.getTitle().equals("百度一下,你就知道")) {
System.out.println("已经回到了百度主页!");
}else {
System.out.println("并没有回到百度主页!");
}
driver.close();
}
}
运行结果:
你学会了吗?