zoukankan      html  css  js  c++  java
  • (九)WebDriver API之定位元素-用By定位

    随笔记录方便自己和同路人查阅。

    #------------------------------------------------我是可耻的分割线-------------------------------------------

      学习selenium自动化之前,最好先学习HTML、CSS、JavaScript等知识,有助于理解定位及操作元素的原理。关于python和selenium安装请自行搜索别的资料,

    这里就不多做介绍了,所有例子均使用python3.6+selenium执行的。

    #------------------------------------------------我是可耻的分割线-------------------------------------------

    By定位

    针对前面介绍的8中定位方法,webdriver还提供了另外一套写法,即统一用find_element()方法,通过By来声明定位的方法,并且传入对应定位方法的定位参考。具体如下:

    find_element(By.ID,”kw”)

    find_element(By.NAME,”WD”)

    find_element(By.CLASS_NAME,”s_ipt”)

    find_element(By.TAG_NAME,”input”)

    find_element(By.LINK_TEXT,”新闻”)

    find_element(By.PARTIAL_LINK_TEXT,”新”)

    find_element(By.XPATH,”//*[@class=’bg s_btn’]”)

    find_element(By.CSS_SELECTOR,”span.bg s_btn_wr>input#su”)

    find_element()方法只用于定位元素,它需要两个参数,第一个参数是定位的类型,由By提供;第二个参数是定位的具体方式。在使用By之前需要将By类导入。

    from selenium.webdriver.common.by import By

    通过查看WebDriver的底层实现代码发现它们其实是一回事儿,例如,find_element_by_id()方法的实现:

    def find_element_by_id(self, id_):
        """Finds an element by id.
    
        :Args:
         - id\_ - The id of the element to be found.
    
        :Returns:
         - WebElement - the element if it was found
    
        :Raises:
         - NoSuchElementException - if the element wasn't found
    
        :Usage:
            element = driver.find_element_by_id('foo')
        """
        return self.find_element(by=By.ID, value=id_)

    WebDriver更推荐前面介绍的写法

  • 相关阅读:
    经典游戏--24点--c++代码实现和总体思路(简单暴力向)
    这么多TiDB负载均衡方案总有一款适合你
    思杰( Citrix)证书的正确处置方式
    从本质彻底精通Git——4个模型1个周期1个史观1个工作流
    HttpClient客户端网络编程——高可用、高并发
    Netty之数据编码
    维吉尼亚密码加解密原理及其实现
    无网环境安装docker之--rpm
    centos7无网环境安装docker
    CentOS8.3最小化安装后安装GNome桌面
  • 原文地址:https://www.cnblogs.com/lirongyang/p/11457510.html
Copyright © 2011-2022 走看看