为了这口醋,包的这饺子。为了Selenium,学有限的CSS,逐步替换XPATH

news2025/2/27 10:26:51

Learn about CSS rules and pseudo-classes to help you move your XPATH locators to CSS.

  • 1. 最基本
        • Id
        • Element Type
        • Direct Child
        • Child or Sub-Child
        • Class
  • 2. 深入一点
      • Next Sibling
        • Attribute Values
        • Choosing a Specific Match
      • Sub-String Matches
  • 3 参考资料

In order for Selenium to click on an element, type into it, or mouse in or out, the tool first needs to find the element.
The WebDriver code library provides methods to do just that, such as

  • findelement()
  • findelements().

These usually take a locator, which can be created by ID, XPATH Code, or Cascading Style Sheets (CSS). Getting the XPATH code can be as easy as selecting the element in developer tools or using something like Chropath.

XPath简单,但不可靠。任何软件升级都有可能造成Path的变化。更不用说反扒技术的存在了。
ID最好,但不常有。
颠来倒去,还是CSS靠谱些。但学起来费劲。

不过,为了Selenium的目的,CSS还是有限费劲,可整。

A CSS Selector is a combination of an element selector and a value which identifies the web element within a web page. They are string representations of HTML tags, attributes, Id and Class. As such they are patterns that match against elements in a tree and are one of several technologies that can be used to select nodes in an XML document.

1. 最基本

Id

An element’s id in XPATH is defined using: [@id='example']and in CSS using: # - ID’s must be unique within the DOM.

XPath: //div[@id='exampleid']
CSS: #exampleid
Element Type

The previous example showed //div in the xpath. That is the element type, which could be input for a text box or button, img for an image, or a for a link.

Xpath: //input or
Css: =input
Direct Child

HTML pages are structured like XML, with children nested inside of parents. If you can locate, for example, the first link within a div, you can construct a string to reach it. A direct child in XPATH is defined by the use of a /, while on CSS, it’s defined using >.

XPath: //div/a
CSS: div > a
Child or Sub-Child

Writing nested divs can get tiring - and result in code that is brittle. Sometimes you expect the code to change, or want to skip layers. If an element could be inside another or one of its children, it’s defined in XPATH using // and in CSS just by a whitespace.

XPath: //div//a
CSS: div a
Class

For classes, things are pretty similar in XPATH: [@class='example'] while in CSS it’s just .


XPath: //div[@class='example']
CSS: .example

2. 深入一点

Next Sibling

This is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username.

<form class = "form-signin" role = "form" action = "/index.php" method = "post">
<h4 class = "form-signin-heading"></h4> 
<input type = "text" class = "form-control" id = "username" name = "username" placeholder = "username" required autofocus></br> 
<input type = "password" class = "form-control" id = "password" name = "password" placeholder = "password" required> 
<p> 
<button class = "btn btn-lg btn-primary btn-block radius" type = "submit" name = "login">Login</button> 
</form> 

Let’s write an XPath and css selector that will choose the input field after “username”. This will select the “alias” input, or will select a different element if the form is reordered.

XPATH: //input[@id='username']/following-sibling:input[1]
CSS: #username + input
Attribute Values

If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form above without adding a class.

We can easily select the username element without adding a class or an id to the element.

XPATH: //input[@name='username']
CSS: input[name='username']

We can even chain filters to be more specific with our selectors.

XPATH: //input[@name='login'and @type='submit']
CSS: input[name='login'][type='submit']

Here Selenium will act on the input field with name=“login” and type=“submit”

Choosing a Specific Match

CSS selectors in Selenium allow us to navigate lists with more finesse than the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type. Nth-child is a pseudo-class. In straight CSS, that allows you to override behavior of certain elements; we can also use it to select those elements.

<ul id = "recordlist">
	<li>Cat</li>
	<li>Dog</li>
	<li>Car</li>
	<li>Goat</li>
</ul>

If we want to select the fourth li element (Goat) in this list, we can use the nth-of-type, which will find the fourth li in the list. Notice the two colons, a recent change to how CSS identifies pseudo-classes.

CSS: #recordlist li::nth-of-type(4)

On the other hand, if we want to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case.

CSS: #recordlist li::nth-child(4)

Note, if you don’t specify a child type for nth-child it will allow you to select the fourth child without regard to type. This may be useful in testing css layout in selenium.

CSS: #recordlist *::nth-child(4)

In XPATH this would be similar to using [4].

Sub-String Matches

CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each:

^= Match a prefix
CSS: a[id^='id_prefix_']

A link with an “id” that starts with the text “id_prefix_”

$= Match a suffix
CSS: a[id$='_id_sufix']

A link with an “id” that ends with the text “_id_sufix”

*= Match a substring
CSS: a[id*='id_pattern']

A link with an “id” that contains the text “id_pattern”

在这里插入图片描述

3 参考资料

  1. Locating Elements
  2. SauceLabs

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1382681.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

java编程解小学生一年级竞赛题

抖音教学视频 目录 1、题目三角形加起来为10 大纲 1、题目三角形加起来为10 连接&#xff1a;小学一年级数学竞赛练习题3套&#xff0c;有点难度&#xff01; 第16题 此方法不是最优解&#xff0c;穷举法&#xff0c;比较暴力解决 主要给大家演示如何用编程去解决我们的实…

格密码基础:SIS问题的定义与理解

目录 一. 介绍 二. SIS问题定义 2.1 直观理解 2.2 数学定义 2.3 基本性质 三. SIS与q-ary格 四. SIS问题的推广 五. Hermite标准型 六. 小结 一. 介绍 short interger solution problem短整数解问题&#xff0c;简称SIS问题。 1996年&#xff0c;Ajtai首次提出SIS问…

Unity Shader 属性的定义

Unity Shader 属性的定义 什么是材质球 人的衣服 什么是shader 决定材质跟灯光的作用 Property 若是把shader看作class&#xff0c;那么Property就可以看成成员变量 属性定义的通用格式 Properites{ Property[Property…] } ep:定义一个int&#xff1a; name("dis…

LLM漫谈(三)| 使用Chainlit和LangChain构建文档问答的LLM应用程序

一、Chainlit介绍 Chainlit是一个开源Python包&#xff0c;旨在彻底改变构建和共享语言模型&#xff08;LM&#xff09;应用程序的方式。Chainlit可以创建用户界面&#xff08;UI&#xff09;&#xff0c;类似于由OpenAI开发的ChatGPT用户界面&#xff0c;Chainlit可以开发类似…

基于TCP的全双工网络编程实践

首先我们先了解一下什么是全双工通信&#xff1f; 全双工数据通信允许数据同时在两个方向上传输&#xff0c;因此&#xff0c;全双工通信相当于是两个单工通信方式的结合&#xff0c;它要求发送设备和接收设备都有独立的接收和发送能力。 TCP服务端代码&#xff1a; #includ…

最新地图下载器(支持切片和矢量数据下载)

一、应用背景 在当今数字时代&#xff0c;地图下载器成为了越来越多人的必备工具。地图下载器可以帮助人们在没有网络的情况下使用地图&#xff0c;也可以帮助人们快速下载大量地图数据&#xff0c;方便日常生活和旅行。本文将介绍地图下载器的基本功能及其在不同场景下的应用。…

RSIC-V“一芯”学习笔记(二)——Linux入门教程

文章目录 一、前言二、Busybox套件三、重要的追踪工具——strace四、Shell五、正则表达式六、重定向&#xff08;多次输入测试时&#xff09;七、一些组合命令八、自动化脚本九、学会查阅十、亲&#xff08;yuan&#xff09;近(li) bai du十一、不要逃避困难十二、重视小问题 一…

springboot集成jsp

首先pom中引入依赖包 <!--引入servlet--> <dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId> </dependency> <!--引入jstl标签库--> <dependency><groupId>javax.servle…

关闭免费版pycharm社区版双击shift时出现的搜索框

Pycharm 在双击 shift 的时候总是弹出搜索框&#xff0c;但作为中国玩家&#xff0c;经常需要双击 shift 循环切换中英文。这就很困恼。 下面就解决这个问题。单独关闭双击shift的功能。 步骤 1.左上角 File -> Settings 2. 如图&#xff0c;输入‘advan’ 找到高级设置&…

Tomcat解压打包文件和并部署

一、文件压缩和上传解压 1.本地打包好dist.tar.gz文件 2.通过xftp拖拽上传到知道文件夹下,或者通过命令: cp dist.tar.gz /path/to/destination/folder注:将dist.tar.gz复制到 /path/to/destination/folder文件夹下,该文件夹只是举个例子怎么复制和解压! 3.进入/path/…

基于TCP的半双工网络编程实践

首先我们先了解一下什么是半双工通信&#xff1f; 半双工数据传输允许数据在两个方向上传输&#xff0c;但是在某一时刻&#xff0c;只允许数据在一个方向上传输&#xff0c;它实际上是一种切换方向的单工通信。 TCP服务端代码&#xff1a; #include <stdio.h> #inclu…

AI手写数字识别(二)

理解代码 上文主要介绍了人工智能模型的集成过程。人工智能模型的正确集成&#xff0c;是我们案例中人工智能应用开发的核心步骤。但要让一个人工智能应用顺利地被使用&#xff0c;除了集成模型之外的一些工作也是必不可少的&#xff0c;比如处理输入的数据&#xff0c;进行界…

Redis:原理速成+项目实战——Redis实战9(秒杀优化)

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位大四、研0学生&#xff0c;正在努力准备大四暑假的实习 &#x1f30c;上期文章&#xff1a;Redis&#xff1a;原理速成项目实战——Redis实战8&#xff08;基于Redis的分布式锁及优化&#xff09; &#x1f4da;订阅专栏&…

瑞_Java开发手册_(三)单元测试

&#x1f64a;前言&#xff1a;本文章为瑞_系列专栏之《Java开发手册》的单元测试篇。由于博主是从阿里的《Java开发手册》学习到Java的编程规约&#xff0c;所以本系列专栏主要以这本书进行讲解和拓展&#xff0c;有需要的小伙伴可以点击链接下载。本文仅供大家交流、学习及研…

使用MATLAB连接USRP

文章目录 前言一、本地环境二、前期准备1、MATLAB版本、labview版本、UHD 版本对应关系2、下载 GNU Radio Companion3、确定 USRP UHD 版本①、下载一个 USRP 硬件驱动程序②、确认 MATLAB 的 UHD 版本 三、下载 USRP 通信工具箱支持包四、使用 MATLAB 连接 USRP 前言 本文记录…

MySQL基础应用之DDL、DCL、DML、DQL

文章目录 前言一、sql基础应用二、列、表属性1、列属性2、表属性 三、sql学习记录---DDL应用之数据库定义语言1、建库规范2、创建库并设置字符集、校验规则3、查看数据库4、删除数据库5、修改数据库字符集 四、sql学习记录---DDL应用之表定义语言1、建表规范2、建表3、查询建表…

Unity中URP中的光照简介

文章目录 前言URP下的光照在Unity中的设置1、主灯设置2、额外灯设置3、反射光设置 前言 我们在这篇文章开始了解URP下的光照。 URP下的光照在Unity中的设置 1、主灯设置 主灯可以选择 禁用 或 逐像素 光照 当选择逐像素光照的主灯后 Cast Shadows&#xff1a;可以选择开启 或…

设计模式之解释器模式【行为型模式】

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档> 学习的最大理由是想摆脱平庸&#xff0c;早一天就多一份人生的精彩&#xff1b;迟一天就多一天平庸的困扰。各位小伙伴&#xff0c;如果您&#xff1a; 想系统/深入学习某…

汽车塑料零件透光率测试仪

塑料透光率测试仪在汽车制造及测试领域中应用广泛&#xff0c;主要用于测量各种玻璃、塑料、薄膜和透明或半透明材料的可见光透射率。 在汽车制造过程中&#xff0c;塑料透光率测试仪可用于检测塑料部件的透光性能。透光率是评估材料质量的重要指标之一&#xff0c;对于汽车的安…

【ArcGIS Pro微课1000例】0057:未安装所需的Microsoft驱动程序

文章目录 一、错误提示二、解决办法1. Excel转表2. Excel转csv一、错误提示 ArcGIS Pro添加Excel数据时,提示未安装所需的Microsoft驱动程序,如下图所示: 二、解决办法 1. Excel转表 在选择输入表时,可能会提示未安装所需的 Microsoft 驱动程序。 这是因为要在 ArcGIS P…