Selenium自动化用法详解【定位页面元素】

简介: Selenium自动化用法详解【定位页面元素】


定位页面元素

id 定位

标签的 id 具有唯一性,就像人的身份证,假设有个 input 标签如下。

<input autocorrect="off" autocomplete="off" name="j_username" id="j_username" placeholder="用户名" type="text" class="normal" autocapitalize="off" aria-label="用户名">

image.gif

我们可以通过 id 定位到它,由于 id 的唯一性,我们可以不用管其他的标签的内容。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumDemo {
    private final static String webDriver = "webdriver.chrome.driver";
    private final static String webDriverPath ="E:\\chromedriver\\chromedriver.exe";
    public static void main(String[] args) {
        System.setProperty(webDriver, webDriverPath);
        WebDriver driver= new ChromeDriver();
        //Jenkins 登录界面
        driver.get("http://119.167.159.214:8080/login");
        //根据用户名输入框id定位
        driver.findElement(By.id("j_username"));
    }
}

image.gif

name 定位

name 指定标签的名称,在页面中可以不唯一。以Jenkins登录页的用户名输入框input为例

<input autocorrect="off" autocomplete="off" name="j_username" id="j_username" placeholder="用户名" type="text" class="normal" autocapitalize="off" aria-label="用户名">

image.gif

我们可以使用 findElement(By.name("j_username")) 定位到 input 标签。

//根据用户名输入框name定位
driver.findElement(By.name("j_username"));

image.gif

class 定位

class 指定标签的类名,在页面中可以不唯一。以Jenkins登录页的登录按钮为例

<input name="Submit" type="submit" value="登录" class="submit-button primary ">

image.gif

我们可以使用 findElement(By.className("submit-button primary")) 定位到 input标签(登录按钮)。

//根据class定位
 driver.findElement(By.className("submit-button primary"));

image.gif

tag 定位

每个 tag 往往用来定义一类功能,所以通过 tag 来识别某个元素的成功率很低,每个页面一般都用很多相同的 tag ,比如:<span>、<a>、<img>、<div>、<input>、<form>等。这里还是用Jenkins登录页面的 form作为例子。

<form method="post" name="login" action="j_spring_security_check"><div class="formRow"><input autocorrect="off" autocomplete="off" name="j_username" id="j_username" placeholder="用户名" type="text" class="normal" autocapitalize="off" aria-label="用户名"></div><div class="formRow"><input name="j_password" placeholder="密码" type="password" class="normal" aria-label="密码"></div><input name="from" type="hidden"><div class="submit formRow"><input name="Submit" type="submit" value="登录" class="submit-button primary "></div><script type="text/javascript">
                  document.getElementById('j_username').focus();
                  var checkBoxClick = function(event) {
                    document.getElementById('remember_me').click();
                  }
                </script><div class="Checkbox Checkbox-medium"><label class="Checkbox-wrapper"><input type="checkbox" id="remember_me" name="remember_me"><div class="Checkbox-indicator"><svg xmlns="http://www.w3.org/2000/svg" height="25" class="svg-icon check" focusable="false" viewBox="0 0 24 24" width="25"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path></svg></div><div class="Checkbox-text">保持登录状态</div></label></div></form>

image.gif

我们可以使用 findElement(By.tagName("form"))定位到 form 标签。

//根据tag定位
  driver.findElement(By.tagName("form"));

image.gif

link 定位

link 专门用来定位文本链接,假如要定位下面这一标签。

<a class="value" href="https://blog.csdn.net/weixin_40986713" target="_blank">洛阳泰山博客</a>

image.gif

我们使用 findElement(By.linkText("洛阳泰山博客"))并指明标签内全部文本即可定位。

driver.findElement(By.linkText("洛阳泰山博客"));

image.gif

partialLinkText 定位

partial_link 翻译过来就是“部分链接”,对于有些文本很长,这时候就可以只指定部分文本即可定位,同样使用刚才的例子。

<a class="value" href="https://blog.csdn.net/weixin_40986713" target="_blank">洛阳泰山博客</a>

image.gif

我们使用 findElement(By.partialLinkText("博客"))并指明标签内全部文本即可定位。

driver.findElement(By.partialLinkText("博客"));

image.gif

xpath定位

xpath 是一种在 XML 文档中定位元素的语言,它拥有多种定位方式,下面通过实例我们看一下它的几种使用方式。下面是Jenkins整个登录页的html代码。

<html lang="zh-CN"><head resurl="/static/70ecc1c9" data-rooturl="" data-resurl="/static/70ecc1c9" data-imagesurl="/static/70ecc1c9/images"><title>登录 [Jenkins]</title><meta name="ROBOTS" content="NOFOLLOW"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/static/70ecc1c9/css/simple-page.css" type="text/css"><link rel="stylesheet" href="/static/70ecc1c9/css/simple-page.theme.css" type="text/css"><link rel="stylesheet" href="/static/70ecc1c9/css/simple-page-forms.css" type="text/css"></head><body><div class="simple-page" role="main"><div class="modal login"><div id="loginIntroDefault"><div class="logo"></div><h1>欢迎来到 Jenkins!</h1></div><form method="post" name="login" action="j_spring_security_check"><div class="formRow"><input autocorrect="off" autocomplete="off" name="j_username" id="j_username" placeholder="用户名" type="text" class="normal" autocapitalize="off" aria-label="用户名"></div><div class="formRow"><input name="j_password" placeholder="密码" type="password" class="normal" aria-label="密码"></div><input name="from" type="hidden"><div class="submit formRow"><input name="Submit" type="submit" value="登录" class="submit-button primary "></div><script type="text/javascript">
                  document.getElementById('j_username').focus();
                  var checkBoxClick = function(event) {
                    document.getElementById('remember_me').click();
                  }
                </script><div class="Checkbox Checkbox-medium"><label class="Checkbox-wrapper"><input type="checkbox" id="remember_me" name="remember_me"><div class="Checkbox-indicator"><svg xmlns="http://www.w3.org/2000/svg" height="25" class="svg-icon check" focusable="false" viewBox="0 0 24 24" width="25"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path></svg></div><div class="Checkbox-text">保持登录状态</div></label></div></form><div class="footer"></div></div></div></body></html>

image.gif

根据上面的标签需要定位 到登录按钮的 input 标签,以下列出了四种方式,xpath 定位的方式多样并不唯一,使用时根据情况进行解析即可。

绝对路径(层级关系)定位

driver.findElement(By.xpath("/html/body/div/div/form/div[2]//input"));

image.gif

相对路径(层级关系)定位

driver.findElement(By.xpath("//form/div[2]//input"));

image.gif

利用元素属性定位

// 利用元素属性定位(有空格的保留空格)
driver.findElement(By.xpath("//*[@class='submit-button primary ']"));

image.gif

注:* 是通配符

层级+元素属性定位

driver.findElement(By.xpath("//div[@class='simple-page']/div/form/div[2]/input"));

image.gif

注:/form/div[2]  代表 form元素下第二个div元素,这个不是数组的下标,第一个元素的下标是1不是0。

逻辑运算符定位

driver.findElement(By.xpath("//*[@class='submit-button primary ' and @type='submit']"));

image.gif

通过文字定位

WebElement login=driver.findElement(By.xpath("//*[text()='登录']"));

image.gif

通过部分文字定位

WebElement login=driver.findElement(By.xpath("//*[contains(text(),''登录)]"));

image.gif

通过部分属性值定位  

driver.findElement(By.xpath("//div[contains(@class,'captcha_verify_img--wrapper')]"));

image.gif

css 定位

1.通过class属性定位

driver.findElement(By.cssSelector(".modal login"));

image.gif

2.通过id属性定位

driver.findElement(By.cssSelector("#loginIntroDefault"));

image.gif

3.通过标签名定位

driver.findElements(By.cssSelector("input"));

image.gif

4.通过父子关系定位

driver.findElements(By.cssSelector("form>div>input"));

image.gif

5.通过属性定位

driver.findElement(By.cssSelector("*[id=loginIntroDefault]"));

image.gif

6.通配符

//选择每一个class属性的值以”_ipt"结尾的元素
driver.findElement(By.cssSelector("[class$=login]"));

image.gif

7.组合定位

driver.findElement(By.cssSelector("form>div>input.submit-button primary "));

image.gif

    • findElement()方法定位元素时,会查询整个DOM,然后返回第一个匹配的元素
    • findElements()方法,可以得到指定规则的集合,适用于需要在一组相似的元素上进行操作的情况。

    定位一组元素

     上 面讲述了定位一个元素的 8 种方法,定位一组元素使用的方法只需要将 findElement 改为 findElements即可,它的使用场景一般是为了批量操作元素。

    这里以 CSDN 首页的一个 作者推荐栏 为例。

    image.gif编辑

    下面用findElements(By.xpath())来定位所有推荐作者的名称。

    <div class="recommendation" data-v-282f7478="" data-v-c95253ce=""><a target="_blank" data-report-click="{&quot;spm&quot;:&quot;1001.2100.3001.7371&quot;}" href="https://blog.csdn.net/ityouknow" class="portrait-box" data-v-282f7478=""><img src="https://profile.csdnimg.cn/1/9/4/1_ityouknow" alt="" class="portrait" data-v-282f7478=""> <img src="https://csdnimg.cn/release/cmsfe/public/img/blog-expert.b9c32f92.png" alt="" class="tag" data-v-282f7478=""> <!----> <!----> <!----></a> <dl data-v-282f7478=""><dt data-v-282f7478=""><a target="_blank" data-report-click="{&quot;spm&quot;:&quot;1001.2100.3001.7371&quot;}" href="https://blog.csdn.net/ityouknow" data-v-282f7478="">微笑很纯洁</a></dt> <dd data-v-282f7478="">一个有故事的程序员,公号:纯洁的微笑,博客:www.ityouknow.com</dd></dl> <div data-report-click="{&quot;spm&quot;:&quot;1001.2100.3001.7372&quot;}" class="recommendation-btn " data-v-282f7478="">关注</div></div>

    image.gif

    代码实现如下:

    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;
    import java.io.IOException;
    import java.util.List;
    public class SeleniumDemo {
        private final static String webDriver = "webdriver.chrome.driver";
        private final static String webDriverPath ="E:\\chromedriver\\chromedriver.exe";
        public static void main(String[] args) throws InterruptedException, IOException {
            System.setProperty(webDriver, webDriverPath);
            WebDriver driver= new ChromeDriver();
            //进入csdn首页
            driver.get("https://blog.csdn.net/");
            Thread.sleep(1000);
            //定位元素
            List<WebElement> elements=driver.findElements(By.xpath("//div[@class='template'][1]/div[2]/div/dl/dt/a"));
            //输入所有作者名
            elements.forEach(e-> System.out.println(e.getText()));
        }
    }

    image.gif

    小结:实际开发过程中,精准的定位到网页元素重中之重,实际开发中,定位元素可能回会不少时间,尤其是设置反爬的网站,定位元素花费的时间可能需要更多时间,比开发的时间还长!!!

    相关文章
    |
    12天前
    |
    数据采集 Web App开发 测试技术
    使用Selenium与WebDriver实现跨浏览器自动化数据抓取
    在网络爬虫领域,Selenium与WebDriver是实现跨浏览器自动化数据抓取的利器。本文详细介绍了如何利用Selenium和WebDriver结合代理IP技术提升数据抓取的稳定性和效率。通过设置user-agent和cookie来模拟真实用户行为,避免被网站检测和阻止。文章提供了具体的代码示例,展示了如何配置代理IP、设置user-agent和cookie,并实现了跨浏览器的数据抓取。合理的参数配置能有效减少爬虫被封禁的风险,提高数据抓取效率。
    使用Selenium与WebDriver实现跨浏览器自动化数据抓取
    |
    11天前
    |
    Web App开发 Java 测试技术
    自动化测试的利器:Selenium WebDriver入门与实践
    【9月更文挑战第8天】在软件开发的海洋中,测试是确保我们不会溺水的那根救生索。Selenium WebDriver,作为自动化测试的明星工具,让这根救生索更加结实可靠。本文将带你快速上手Selenium WebDriver,从基础设置到实际操作,再到实战演练,让你的开发之旅更加平稳顺畅。
    |
    5天前
    |
    敏捷开发 Java 测试技术
    探索自动化测试的奥秘:从Selenium到Appium
    【9月更文挑战第14天】软件测试,这个看似枯燥乏味却至关重要的领域,正经历着一场革命。随着技术的进步,自动化测试工具如Selenium和Appium已成为质量保证的利器。本文将带你一探这些工具的神秘面纱,了解它们如何简化测试流程、提升效率,并确保软件产品的质量。准备好,我们将深入自动化测试的世界,解锁其背后的原理和实践技巧。
    |
    7天前
    |
    敏捷开发 测试技术 持续交付
    自动化测试之美:如何用Selenium和Python打造高效测试脚本
    【9月更文挑战第13天】在软件开发的海洋中,自动化测试是那抹不可或缺的亮色。它不仅提升了测试效率,还保障了产品质量。本文将带你领略使用Selenium和Python构建自动化测试脚本的魅力所在,从环境的搭建到脚本的编写,再到问题的排查,每一步都是对软件质量把控的深刻理解和实践。让我们开始这段探索之旅,解锁自动化测试的秘密吧!
    8 0
    |
    20天前
    |
    Web App开发 机器学习/深度学习 测试技术
    软件测试中的自动化策略:以Selenium为例
    【8月更文挑战第31天】在软件开发周期中,测试环节扮演着至关重要的角色。随着敏捷开发的兴起,自动化测试成为提升效率和确保产品质量的关键手段。本文将介绍如何利用Selenium工具实现软件的自动化测试,从搭建环境到编写测试脚本,再到执行和分析结果,我们将一步步揭示自动化测试的全过程。文章旨在通过具体示例,帮助读者理解并运用自动化测试技术,提高测试工作的效率和效果。
    |
    21天前
    |
    Web App开发 测试技术 API
    自动化测试之美:使用Selenium和Python进行Web应用测试
    【8月更文挑战第31天】在软件开发的快节奏世界中,自动化测试如同一束明灯,照亮了质量保证之路。本文将引导你通过Selenium和Python的强大组合,探索如何构建高效的Web应用测试框架。我们不仅会讨论理论,还会深入代码,从一个简单的示例开始,逐步扩展至更复杂的场景。无论你是初学者还是有经验的开发者,这篇文章都将为你提供宝贵的见解和实用的技巧。让我们一同揭开自动化测试的神秘面纱,体验它的魅力所在。
    |
    7天前
    |
    JavaScript 前端开发 测试技术
    Selenium2Library实现基于GUI的测试
    Selenium2Library实现基于GUI的测试
    15 0
    |
    20天前
    |
    Web App开发 Java 测试技术
    自动化测试的新篇章:使用Selenium WebDriver进行高效测试
    【8月更文挑战第31天】 在软件开发的海洋中,自动化测试犹如一艘航船,带领着质量保证团队驶向效率与精准的彼岸。本文将揭开Selenium WebDriver的神秘面纱,通过实际案例引导您掌握这一强大的自动化测试工具。我们将从Selenium WebDriver的基础概念出发,逐步深入到代码示例,最后探讨其在现实项目中的应用场景和优势,旨在为您的软件测试之旅提供清晰的指南。
    |
    20天前
    |
    Web App开发 测试技术 持续交付
    探索自动化测试:以Selenium和Python为例
    【8月更文挑战第31天】自动化测试在现代软件开发中扮演着不可或缺的角色。本文将通过一个简化的示例,展示如何使用Selenium和Python进行Web应用的自动化测试。我们将从安装必要的工具开始,逐步构建一个简单的测试脚本,并执行它来验证其功能。通过这个过程,我们旨在揭示自动化测试的价值,并激励读者深入探索这一领域。
    |
    20天前
    |
    Web App开发 IDE 测试技术
    自动化测试的利器:Selenium 框架深度解析
    【8月更文挑战第31天】在软件开发的世界中,自动化测试是提高产品质量和开发效率不可或缺的一环。本文将深入探讨Selenium这一强大的自动化测试工具,从其架构、优势到实战应用,一步步揭示如何利用Selenium框架提升软件测试的效率和准确性。通过具体的代码示例,我们将展示Selenium如何简化测试流程,帮助开发者快速定位问题,确保软件的稳定性和可靠性。无论你是测试新手还是资深开发者,这篇文章都将为你打开一扇通往高效自动化测试的大门。

    热门文章

    最新文章