谈谈selenium4.0中的相对定位

这篇具有很好参考价值的文章主要介绍了谈谈selenium4.0中的相对定位。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

相对定位历史

  • 2021-10-13 发布的 selenium 4.0 开始引入,selenium 3.X是没有的
implement relative locator for find_element (#9902)
  • 4.10维护了下
Improve near relative locator behavior (#11290)

其他都是文档、异常信息方面的处理

实例演示

D:\selenium\demo\relative.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>relative</title>
</head>
<body>
    DATE:<input id="date" type="text">
    USER:<input id="username" type="text"><br>
    CODE:<input id="code" type="text">
    PASS:<input id="password" type="text">
</body>
</html>

如下界面

谈谈selenium4.0中的相对定位,Selenium杂记,python,开发语言

实例代码

from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with


from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get(r'D:\selenium\demo\relative.html')
ele_date = driver.find_element('id','date')
ele_code = driver.find_element('id','code')
ele_user = driver.find_element('id','username')
ele_password = driver.find_element('id','password')

driver.find_element(locate_with(By.CSS_SELECTOR, "input").above(ele_code)).send_keys('code aboe')
driver.find_element(locate_with(By.CSS_SELECTOR, "input").below(ele_user)).send_keys('user below')
driver.find_element(locate_with(By.CSS_SELECTOR, "input").to_left_of(ele_password)).send_keys('pass left')
driver.find_element(locate_with(By.CSS_SELECTOR, "input").to_right_of(ele_date)).send_keys('date right')
driver.find_element(locate_with(By.CSS_SELECTOR, "input").near(ele_code)).send_keys('code near')

执行效果

谈谈selenium4.0中的相对定位,Selenium杂记,python,开发语言

相关源码说明

find_element

在find_element的源码中有这么一段

    def find_element(self, by=By.ID, value=None) -> WebElement:
        if isinstance(by, RelativeBy):
            elements = self.find_elements(by=by, value=value)
            if not elements:
                raise NoSuchElementException(f"Cannot locate relative element with: {by.root}")
            return elements[0]

也就是说你传入的by不仅仅可以是下面这8个,还可以是RelativeBy对象

class By:
    """
    Set of supported locator strategies.
    """

    ID = "id"
    XPATH = "xpath"
    LINK_TEXT = "link text"
    PARTIAL_LINK_TEXT = "partial link text"
    NAME = "name"
    TAG_NAME = "tag name"
    CLASS_NAME = "class name"
    CSS_SELECTOR = "css selector"

那如果是RelativeBy对象的话,会去调用find_elements,self.find_elements(by=by, value=value)

    def find_elements(self, by=By.ID, value=None) -> List[WebElement]:
    	if isinstance(by, RelativeBy):
            _pkg = '.'.join(__name__.split('.')[:-1])
            raw_function = pkgutil.get_data(_pkg, 'findElements.js').decode('utf8')
            find_element_js = f"return ({raw_function}).apply(null, arguments);"
            return self.execute_script(find_element_js, by.to_dict())

if语句下的2行代码就是在加载findElements.js

最后两句就是构造一个js然后去执行它,细节就不追究了

RelativeBy

这个class位于selenium\webdriver\support\relative_locator.py

class RelativeBy:
    def __init__(self, root: Dict[By, str] = None, filters: List = None):
        self.root = root
        self.filters = filters or []
        
    def above(self, element_or_locator: Union[WebElement, Dict] = None) -> "RelativeBy":
        if not element_or_locator:
            raise WebDriverException("Element or locator must be given when calling above method")

        self.filters.append({"kind": "above", "args": [element_or_locator]})
        return self

这个类提供了5个用于定位的实例方法:above below to_left_of to_right_of near

可以看到RelativeBy对象的实例化需要2个参数,一个是root:dict类型,一个是filters : 列表类型

可以看到above这样的方法其实没做啥,关键是对self.filters的一个处理,增加一个对应kind(与方法同名)和args,这个args操作你要去参考的元素的定位器或WebElement

locate_with

在实例代码中,我们用到了locate_with这个函数,这个函数跟RelativeBy在同一个文件中

代码如下

def locate_with(by: By, using: str) -> "RelativeBy":
    assert by is not None, "Please pass in a by argument"
    assert using is not None, "Please pass in a using argument"
    return RelativeBy({by: using})

可以看到它确实是返回了一个RelativeBy的实例对象

而它的用法跟我们的find_element就一致了,唯一的不同就是参数名,这边是using,find_element是value

为何用它的另一方面原因是在RelativeBy的doc中这样的一段描述

        Example:
            lowest = driver.find_element(By.ID, "below")

            elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").above(lowest))

说在最后

这东西我在工作中没有用过,因为它出生后我就进入了…

使用过一些常见去测试它的效果,并不理想,不过是在早期的版本中做的,现在不清楚是否好用一些

溯源的话应该可以追溯到js中吧,有空找下,或者哪个大佬知道的可以指点下文章来源地址https://www.toymoban.com/news/detail-762323.html

到了这里,关于谈谈selenium4.0中的相对定位的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 关于selenium4.0版本在springboot中的使用问题

    年底不是紧张的日子,想着写一个程序来进行订饭,首先想到了用selenium来进行开发,但是在开发的过程中遇到了问题。 添加上了jar包,写好了代码就测试时发现出现了异常。 java.lang.NoClassDefFoundError: org/openqa/selenium/internal/Require  Caused by: java.lang.ClassNotFoundException: org.openqa.s

    2024年02月05日
    浏览(27)
  • 谈谈selenium中的clear后输入内容异常的处理

    项目的登录:http://124.223.31.21:9097/#/ ; 可能会无法访问,了解下这个情况的处理即可 代码 你会发现无法登录,道理很简单 你输入的密码追加过去了,send_keys如果之前有内容,是会保留的,追加你输入的内容。 你可能会这样处理,在密码元素上先清空之前的内容(clear),然后

    2024年02月01日
    浏览(32)
  • 盘点selenium4和selenium3的区别

    在某些情况下,升级仍然会存在依赖项的问题,比如使用python的pip进行selenium安装的时候会出现依赖异常。 一、升级依赖关系 使用 Python 的最重要变化是所需的最低版本,Selenium 4 将至少需要 Python 3.7 或更高版本。 在python环境下,基于pip命令行做升级的话, 你可以执行: 1、

    2024年04月25日
    浏览(26)
  • selenium4框架学习

    https://blog.csdn.net/qq_45158700/article/details/135363339 浏览器驱动selenium文档下载 Selenium with Python中文翻译文档:https://selenium-python-zh.readthedocs.io/en/latest/ 下面链接中为103.0.5060.53版本的浏览器和对应的chromedriver ​链接:https://pan.baidu.com/s/1rMniL41_L05ucgwGPzhn2A ​提取码:6byo 谷歌浏览器和

    2024年01月21日
    浏览(34)
  • Selenium 定位伪元素,获取伪元素中的文本

    伪元素的定义:         不是真正的页面元素,html没有对应的元素,但是其所有用法和表现行为与真正的页面元素一样,可以对其使用诸如页面元素一样的css样式,表面上看上去貌似是页面的某些元素来展现,实际上是css样式展现的行为,因此被称为伪元素。  前端有些

    2024年04月14日
    浏览(31)
  • Selenium4自动化测试框架

    Selenium 介绍 Selenium 是目前用的最广泛的 Web UI 自动化测试框架,核心功能就是可以在多个浏览器上进行自动化测试,支持多种编程语言,目前已经被 google,百度,腾讯等公司广泛使用。 1、配置 google 驱动的环境变量,如果不配置需要在代码中指定驱动位置。 2、eclipse 中导入

    2024年02月03日
    浏览(34)
  • 【Python爬虫 • selenium】selenium4新版本自动获取驱动的常见问题

    关于上次发布的文章《【Python爬虫 • selenium】selenium4新版本使用指南》很多人反馈说自动获取的驱动会导致闪退,本次文章给出详细配置。 首先说一下大家闪退的问题。我在低版本的python中,安装selenium,发现安装的是旧版本,并不是selenium4的版本,就导致用法还是selenium

    2024年01月17日
    浏览(44)
  • Linux环境下运行selenium4.14

    使用Python爬虫爬取数据时,需要用到selenium,在服务器上运行时,需要如下配置: 1、安装谷歌浏览器 yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm -y 2、安装 chromedriver 1)运行下面命令查看浏览器版本 2) 根据谷歌浏览器版本下载对应的浏览器驱动版本

    2024年02月06日
    浏览(27)
  • selenium4.3.0模块中的find_element_by_id方法无法使用,改用driver.find_element(by=By.ID, value=None)

    在selenium最新版本4.3.0中, 使用之前的find_element_by_id会报错 Ctrl+点击find_element,查看代码 最新版本,改为了driver.find_element(By.ID, ‘foo’) 在自己的代码中修改,发现By会被pycharm下划线提示报错,再次查看代码 发现需要import By 再次修改自己的代码,运行通过

    2024年02月13日
    浏览(34)
  • python中selenium如何定位shadow-root中的元素

    最近遇到了这个问题,找了好久,终于找到了,参考的是下面这篇文章,但是这篇文章写的比较简单并且有点小问题,对此进行补充,和记录关于shadow-root的查找_#shadow-root_Redamancy又在写BUG的博客-CSDN博客 是以下面这个图片为例,要定位到里面的input需要这么写: 后面如果有多

    2024年02月03日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包