selenium 八大元素定位方法
作者:互联网
from selenium import webdriver from time import sleep from selenium.webdriver.common.by import By class Testcase(object): def __init__(self): self.driver = webdriver.Chrome() self.driver.get("http://www.baidu.com") self.driver.maximize_window() sleep(1) def test_id(self): # id是唯一的 element = self.driver.find_element_by_id("kw") element.send_keys("selenium") print(type(element)) self.driver.find_element_by_id("su").click() sleep(3) # self.driver.quit() def test_name(self): # find_element_by_name 方法可能返回多个元素,返回第一个 # self.driver.find_elements_by_name() 返回一个集合 self.driver.find_element_by_name("wd").send_keys("selenium") self.driver.find_element_by_id("su").click() sleep(3) self.driver.quit() def test_link(self): self.test_id() # link_text 链接文本 self.driver.find_element_by_link_text("百度首页").click() sleep(3) self.driver.quit() def test_particial_link_text(self): self.test_id() # 一部分 self.driver.find_element_by_partial_link_text("首页").click() sleep(3) self.driver.quit() def test_xpath(self): self.driver.find_element_by_xpath('//*[@id="kw"]').send_keys("selenium") self.driver.find_element_by_id("su").click() sleep(3) self.driver.quit() def test_tag(self): # 根据名称定位,用的比较少 没法准确定位 test = self.driver.find_element_by_tag_name('input') print(test) def test_css_selector(self): # copy selector self.driver.find_element_by_css_selector('#kw').send_keys("selenium") self.driver.find_element_by_id("su").click() sleep(3) self.driver.quit() def test_class_name(self): self.driver.find_element_by_class_name('s_ipt').send_keys("selenium") self.driver.find_element_by_id("su").click() sleep(3) self.driver.quit() def test_all(self): self.driver.find_element(By.ID, value="kw").send_keys("selenium") self.driver.find_element_by_id("su").click() sleep(3) self.driver.quit() if __name__ == '__main__': case = Testcase() case1 = case.test_all()
from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep def get_element(driver, *loc): e = driver.find_element(*loc) return e if __name__ == '__main__': driver = webdriver.Chrome() driver.get("http://www.baidu.com") driver.maximize_window() loc = (By.ID, "kw") loc2 = (By.ID, "su") sleep(1) get_element(driver, *loc).send_keys("selenium") get_element(driver, *loc2).click() sleep(4) driver.quit()
标签:定位,八大,selenium,self,driver,element,sleep,test,find 来源: https://www.cnblogs.com/xytyyds/p/15975907.html