selenium By定位

使用By定位前,首先导入By模块

from selenium.webdriver.common.by import By 

By定位的语法:

  1. find_element(By.ID,"kw")
  2. find_element(By.NAME,"wd")
  3. find_element(By.CLASS_NAME,"s_ipt")
  4. find_element(By.TAG_NAME,"input")
  5. find_element(By.LINK_TEXT,u"新闻")
  6. find_element(By.PARTIAL_LINK_TEXT,u"新")
  7. find_element(By.XPATH,"//*[@class='bg s_btn']")
  8. find_element(By.CSS_SELECTOR,"span.bg s_btn_wr>input#su")

封装:

from selenium import webdriver
from selenium.webdriver.common.by import By


class ByFind:
    def __init__(self):
        self.driver = webdriver.Chrome()

    def by(self, *args):
        """使用By进行元素定位"""
        loc = args[0]
        if loc[0] == 'id':
            return self.driver.find_element(By.ID, loc[1])
        elif loc[0] == 'name':
            return self.driver.find_element(By.NAME, loc[1])
        elif loc[0] == 'tag_name':
            return self.driver.find_element(By.TAG_NAME, loc[1])
        elif loc[0] == 'class_name':
            return self.driver.find_element(By.CLASS_NAME, loc[1])
        elif loc[0] == 'link_text':
            return self.driver.find_element(By.LINK_TEXT, loc[1])
        elif loc[0] == 'partial_link_text':
            return self.driver.find_element(By.PARTIAL_LINK_TEXT, loc[1])
        elif loc[0] == 'xpath':
            return self.driver.find_element(By.XPATH, loc[1])
        elif loc[0] == 'css':
            return self.driver.find_element(By.CSS_SELECTOR, loc[1])
        else:
            print("方法未找到...")


if __name__ == '__main__':
    element = ('id', 'su')
    b = ByFind()
    b.by(element)

 

你可能感兴趣的:(自动化测试,selenium)