selenium源码通读·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 = "...
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()
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)