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 实例
# -*- 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()