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更推荐前面介绍的写法

  • 相关阅读:
    Django中的session的使用
    《Vue笔记01: 我与唐金州二三事》
    CSS之border绘制三角形
    如何增强前端代码的健壮性
    flex招式心法
    码出优美
    可保图片不变形的object-fit
    three.js基础前置知识
    【JS档案揭秘】第四集 关于this的讨论到此为止
    【JS档案揭秘】第三集 深入最底层探秘原型链
  • 原文地址:https://www.cnblogs.com/lirongyang/p/11457510.html
Copyright © 2011-2022 走看看