前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Selenium Webdriver之点击图像链接

Selenium Webdriver之点击图像链接

作者头像
软测小生
发布2019-09-10 17:26:39
2.3K0
发布2019-09-10 17:26:39
举报
文章被收录于专栏:软测小生软测小生

访问图片链接

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

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

在这种情况下,我们应该使用任意一种方法:cssSelectorBy.xpath,第一种方法更受欢迎,因为它简单实用。

在下面的示例中,我们将访问Baidu搜索内容之后页面上的Baidu徽标,点击之后将回到百度主页面,在日常工作中很容易遇到这样的情况,一般都是出现产品的Logo或者公司的Logo,点击之后就会返回产品能够主页面或者公司主页面,上面的百度是一个,再比如淘宝网,京东等等,所有的页面都会有Logo图,都可以再点击之后回到主页。

元素以及定位

我们将使用By.cssSelector和元素的“title”属性来访问图像链接。然后我们将验证点击之后是否会跳转到对应的页面上。

代码语言:javascript
复制
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();
    }
}

运行结果:

运行结果

你学会了吗?

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 软测小生 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档