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

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

    相关文章
    |
    3月前
    |
    数据采集 测试技术 Python
    自动化淘宝秒杀:使用Selenium WebDriver的实战指南
    本文详细介绍了如何利用Selenium WebDriver自动化淘宝秒杀操作,包括环境配置、代码实现及注意事项,旨在帮助读者提升秒杀成功率,同时提醒合理使用以遵守平台规则。
    188 8
    |
    2月前
    |
    Web App开发 数据采集 JavaScript
    CDP与Selenium相结合——玩转网页端自动化数据采集/爬取程序
    本文介绍了Selenium、Chrome DevTools及Chrome DevTools Protocol (CDP) 的基本功能与应用。Selenium是一款开源自动化测试工具,适用于网页端应用程序测试和数据采集,具备跨平台特性。Chrome DevTools内置浏览器中,提供调试、分析Web应用程序的功能,包括元素、控制台、源代码和网络选项卡等。CDP是一套用于与Chromium内核浏览器通信的API,支持自动化测试和性能分析。文中还展示了Selenium与CDP结合使用的示例,如捕获网络请求数据和打印网页内容,并推荐了相关书籍和资源以供深入学习。
    404 39
    CDP与Selenium相结合——玩转网页端自动化数据采集/爬取程序
    |
    2月前
    |
    Web App开发 IDE JavaScript
    Selenium IDE:Web自动化测试的得力助手
    Selenium IDE:Web自动化测试的利器。作为开源工具,Selenium IDE支持录制与回放用户操作,适用于Chrome、Firefox等多浏览器,简化了测试流程,提升了效率,降低了自动化测试的门槛。它还支持导出多种编程语言的脚本,便于测试集成与复用。
    155 31
    Selenium IDE:Web自动化测试的得力助手
    |
    2月前
    |
    Web App开发 IDE 测试技术
    Selenium:强大的 Web 自动化测试工具
    Selenium 是一款强大的 Web 自动化测试工具,包括 Selenium IDE、WebDriver 和 Grid 三大组件,支持多种编程语言和跨平台操作。它能有效提高测试效率,解决跨浏览器兼容性问题,进行性能测试和数据驱动测试,尽管存在学习曲线较陡、不稳定等缺点,但其优势明显,是自动化测试领域的首选工具。
    282 17
    Selenium:强大的 Web 自动化测试工具
    |
    3月前
    |
    Web App开发 设计模式 JavaScript
    自动化测试之美:如何利用Selenium实现Web应用的高效测试
    【10月更文挑战第29天】在软件开发的世界中,测试是确保产品质量的关键步骤。本文将带你了解如何使用Selenium这一强大的自动化测试工具,提高Web应用测试的效率和准确性。通过实际案例,我们将探索Selenium的核心功能及其在现代软件开发中的应用,旨在帮助读者掌握自动化测试的精髓,从而提升软件测试工作的整体效能。
    86 0
    |
    4月前
    |
    Web App开发 前端开发 JavaScript
    探索Python科学计算的边界:利用Selenium进行Web应用性能测试与优化
    【10月更文挑战第6天】随着互联网技术的发展,Web应用程序已经成为人们日常生活和工作中不可或缺的一部分。这些应用不仅需要提供丰富的功能,还必须具备良好的性能表现以保证用户体验。性能测试是确保Web应用能够快速响应用户请求并处理大量并发访问的关键步骤之一。本文将探讨如何使用Python结合Selenium来进行Web应用的性能测试,并通过实际代码示例展示如何识别瓶颈及优化应用。
    244 5
    |
    4月前
    |
    Java 测试技术 C#
    自动化测试之美:从Selenium到Appium
    【10月更文挑战第3天】在软件开发的海洋中,自动化测试如同一艘航船,引领着质量保证的方向。本文将带你领略自动化测试的魅力,从Web端的Selenium到移动端的Appium,我们将一探究竟,看看这些工具如何帮助我们高效地进行软件测试。你将了解到,自动化测试不仅仅是技术的展示,更是一种提升开发效率和产品质量的智慧选择。让我们一起启航,探索自动化测试的世界!
    |
    4月前
    |
    JavaScript 前端开发 测试技术
    精通Selenium:从基础到高级的网页自动化测试策略
    【10月更文挑战第6天】随着Web应用变得越来越复杂,手动进行功能和兼容性测试变得既耗时又容易出错。自动化测试因此成为了现代软件开发不可或缺的一部分。Selenium是一个强大的工具集,它支持多种编程语言(包括Python),允许开发者编写脚本来模拟用户与Web页面的交互。本文将带领读者从Selenium的基础知识出发,逐步深入到高级的应用场景,通过丰富的代码示例来展示如何高效地进行网页自动化测试。
    1017 5
    |
    4月前
    |
    Web App开发 IDE 测试技术
    自动化测试的利器:Selenium 框架深度解析
    【10月更文挑战第2天】在软件开发的海洋中,自动化测试犹如一艘救生艇,让质量保证的过程更加高效与精准。本文将深入探索Selenium这一强大的自动化测试框架,从其架构到实际应用,带领读者领略自动化测试的魅力和力量。通过直观的示例和清晰的步骤,我们将一起学习如何利用Selenium来提升软件测试的效率和覆盖率。
    |
    4月前
    |
    Web App开发 缓存 Linux
    高效Selenium测试技巧:轻松控制已开启的浏览器
    【10月更文挑战第13天】在进行Selenium测试时,通常会启动新浏览器实例,但有时需要控制已开启的浏览器,以节省时间并更真实地模拟用户行为。这可通过设置Chrome为可远程控制并使用`Remote WebDriver`连接实现。需在启动Chrome时添加`--remote-debugging-port`参数,并通过Python脚本中的`webdriver.Remote`连接至指定端口。此外,还可利用会话ID(Session ID)重新连接浏览器,提高测试灵活性。需要注意浏览器版本兼容性及元素定位稳定性等问题,确保测试准确性和一致性。
    536 1

    热门文章

    最新文章