selenium源码通读·7 |webdriver/common/by.py-By类分析

Posted NoamaNelson

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selenium源码通读·7 |webdriver/common/by.py-By类分析相关的知识,希望对你有一定的参考价值。

·7 |webdriver/common/by.py-By类分析

1 源码路径

selenium/webdriver/common/by.py

2 功能描述

  • 翻译:一组受支持的定位器策略,即支持的定位方式
  • 定位方式包含八种:
class By(object):
    """
    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"

3 使用方法

  • 例如:
driver.find_element(By.ID, "xx").click()
  • 另一种写法:
driver.find_element_by_id( "xx").click()
  • 两种写法的区别,我们查看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_)
  • 从上发现其实,find_element_by_id的方法是根据By.ID来实现的,所以两种方式都是可以的;
  • 其他的定位方式都是类似的。

4 实例

  • 替换之前的定位方式为By.ID
# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2022/5/17
# 文件名称:selen_by.py
# 作用:验证By方法
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

# driver.find_element_by_id("kw").send_keys("NoamaNelson")
driver.find_element(By.ID, "kw").send_keys("NoamaNelson")
time.sleep(1)
# driver.find_element_by_id("kw").send_keys(Keys.ENTER)
driver.find_element(By.ID, "kw").send_keys(Keys.ENTER)
driver.maximize_window()
time.sleep(0.5)
# driver.find_element_by_id("kw").send_keys(Keys.CONTROL,"a")
driver.find_element(By.ID, "kw").send_keys(Keys.CONTROL, "a")
time.sleep(0.5)
# driver.find_element_by_id("kw").send_keys("N")
driver.find_element(By.ID, "kw").send_keys("N")
# su = driver.find_element_by_id("su")
su = driver.find_element(By.ID, "su")
ActionChains(driver).click(su).perform()
time.sleep(1)
driver.quit()

『全栈测试技术,分享,共勉,共进,提升』


以上是关于selenium源码通读·7 |webdriver/common/by.py-By类分析的主要内容,如果未能解决你的问题,请参考以下文章

selenium源码通读·12 |webdriver/remote分析

selenium源码通读·12 |webdriver/remote分析

selenium源码通读·13 |webdriver/support分析

selenium源码通读·4 |webdriver/common分析

selenium源码通读·3 | 从源码看引入webdriver包的原因

selenium源码通读·11 |webdriver/common/touch_actions.py-TouchActions类分析