在web自动化学习01——单个元素定位方式中定位元素可以使用find_element_by_id(),find_element_by_class_name(),...,等方式。然而还有另外一种方式可以定位元素,就是By。
前提:引入By包 from selenium.webdriver.common.by import By
定位方式:
1)find_element(By.ID,‘ID值‘)
2)find_element(By.CLASS_NAME,‘CLASS_NAME值‘)
3)find_element(By.NAME,‘NAME值‘)
4)find_element(By.TAG_NAME,‘TAG_NAME值‘) (不推荐:一般tag_name用来进行多元素定位)
5)find_element(By.LINK_TEXT,‘LINK_TEXT值‘)
6)find_element(By.PARTIAL_LINK_TEXT,‘PARTIAL_LINK_TEXT值‘)
7)find_element(By.CSS_SELECTOR,‘CSS_SELECTOR值‘)
8)find_element(By.XPATH,‘XPATH值‘)
from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep class elementLocator_by(): ‘‘‘ BY方式有: 1)find_element(By.id,‘id值‘) ‘‘‘ def __init__(self): #加启动配置 option = webdriver.ChromeOptions() # 关闭“chrome正受到自动测试软件的控制” option.add_experimental_option(‘useAutomationExtension‘,False) option.add_experimental_option(‘excludeSwitches‘, [‘enable-automation‘]) #不自动关闭浏览器 option.add_experimental_option(‘detach‘,True) self.driver = webdriver.Chrome(chrome_options=option) self.driver.get("http://www.baidu.com") self.driver.maximize_window() #By.ID def elementLocator_by_ID(self): #定位到搜索输入框 search_input = self.driver.find_element(By.ID,‘kw‘) #输入webdriver search_input.send_keys("webdriver") #定位到搜索按钮 search_button = self.driver.find_element(By.ID,‘su‘) #点击搜索按钮 search_button.click() #By.CLASS_NAME def elementLocator_by_CLASS_NAME(self): #定位到搜索输入框 search_input = self.driver.find_element(By.CLASS_NAME,‘s_ipt‘) #输入google浏览器 search_input.send_keys("google浏览器") #定位到搜索按钮 search_button = self.driver.find_element(By.CLASS_NAME,‘s_btn‘) #点击搜索按钮 search_button.click() #By.NAME def elementLocator_by_NAME(self): #定位到搜索输入框 search_input = self.driver.find_element(By.NAME,‘wd‘) #输入今日头条 search_input.send_keys("今日头条") #定位到搜索按钮 search_button = self.driver.find_element(By.CLASS_NAME,‘s_btn‘) #点击搜索按钮 search_button.click() #By.TAG_NAME def elementLocator_by_TAG_NAME(self): pass #By.LINK_TEXT def elementLocator_by_LINK_TEXT(self): # 定位到新闻链接入口 news_href = self.driver.find_element(By.LINK_TEXT, ‘新闻‘) # 点击新闻按钮 news_href.click() #By.PARTIAL_LINK_TEXT def elementLocator_by_PARTIAL_LINK_TEXT(self): # 定位到新闻链接入口 news_href = self.driver.find_element(By.PARTIAL_LINK_TEXT, ‘闻‘) # 点击新闻按钮 news_href.click() #By.CSS_SELECTOR def elementLocator_by_CSS_SELECTOR(self): # 定位到地图链接入口 map_href = self.driver.find_element(By.CSS_SELECTOR, ‘#s-top-left > a:nth-child(3)‘) # 点击地图按钮 map_href.click() #By.XPATH def elementLocator_by_XPATH(self): # 定位到登录入口 login_button = self.driver.find_element(By.XPATH, "//a[@id=‘s-top-loginbtn‘]") # 点击登录按钮 login_button.click() elementLocator_by().elementLocator_by_XPATH()