如何在Selenium Webdriver中点击图像链接

文章首发于微信公众号:软测小生

访问图片链接

图像链接是Web页面中由图像表示的链接,当点击该图片(链接)时,将导航到另一个窗口或页面。

因为它们是图像,所以我们不能使用**By.linkText()By.partialLinkText()**方法,因为图像链接基本上没有链接文本。

在这种情况下,我们应该使用任意一种方法:cssSelectorBy.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();
	}
}

运行结果:
在这里插入图片描述

你学会了吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软测小生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值