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

  • 相关阅读:
    ==和equals
    java 多重继承
    java单例模式
    基础小知识
    print流之错误日志
    print流
    实现读文本文件(IOl流)
    缓冲流(数据的复制粘贴)IO流
    力扣20题、1047(括号合法性,删除字符串中的所有相邻重复项)
    力扣232题、225题(栈实现队列,队列实现栈)
  • 原文地址:https://www.cnblogs.com/lirongyang/p/11457510.html
Copyright © 2011-2022 走看看