selenium学习笔记02-selenium定位的八大方法
selenium实现元素定位
要操作web界面上元素,首先要定位到该元素
from selenium import webdriver from time import sleep # from .chrome.webdriver import WebDriver as Chrome # noqa 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): # 返回唯一 element = self.driver.find_element_by_id('kw') element.send_keys('selenium') print(type(element)) # <class 'selenium.webdriver.remote.webelement.WebElement'> self.driver.find_element_by_id('su').click() sleep(3) # self.driver.quit() def test_name(self): # 方法可能返回多个元素,返回第一个 # self.driver.find_elements_by_name()返回一个集合 self.driver.find_elements_by_name('wd').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(3) self.driver.quit() def test_linktext(self): self.test_id() self.driver.find_element_by_link_text('百度首页').click() sleep(3) self.driver.quit() def test_partial_linktext(self): self.test_id() self.driver.find_element_by_partial_link_text('百度').click() sleep(3) self.driver.quit() def text_xpath(self): self.driver.find_element_by_xpath('//*[@id="kw"]').send_keys('xpath') self.driver.find_element_by_id('su').click() def text_tag(self): # 返回一个集合 input = self.driver.find_element_by_tag_name('input') print(input) def text_css_selector(self): self.driver.find_element_by_css_selector('#kw').send_keys('selenium') self.driver.find_element_by_id('su').click() def text_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 text_all(self): self.driver.find_element(value='kw').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(3) self.driver.quit() if __name__ =="__main__": case = TestCase() # case.test_id() # case.test_name() # case.test_linktext() # case.test_partial_linktext() # case.test_partial_linktext() # case.text_tag() # case.text_css_selector() # case.text_class_name() case.text_all()
提取,封装,做公共部分
from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By def get_element(driver,*log): e = driver.find_element(*log) return e if __name__ == "__main__": driver = webdriver.Chrome() driver.get("http://www.baidu.com") sleep(1) get_element(driver, By.ID, 'kw').send_keys('selenium') get_element(driver, By.ID, 'su').click()