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

2023-02-09 14:48:41 浏览数 (1)

1 源码路径

代码语言:python代码运行次数:0复制
selenium/webdriver/common/by.py
在这里插入图片描述在这里插入图片描述

2 功能描述

  • 翻译:一组受支持的定位器策略,即支持的定位方式
  • 定位方式包含八种:
代码语言:python代码运行次数:0复制
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 使用方法

  • 例如:
代码语言:python代码运行次数:0复制
driver.find_element(By.ID, "xx").click()
  • 另一种写法:
代码语言:python代码运行次数:0复制
driver.find_element_by_id( "xx").click()
  • 两种写法的区别,我们查看find_element_by_id的源码:
代码语言:python代码运行次数:0复制
    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
代码语言:python代码运行次数:0复制
# -*- 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()

0 人点赞