一、执行环境
Python 3.12.0 selenium 3.14.0
二、八大元素定位
//示例:打开百度,输入123,点击搜索 from selenium import webdriver from time import sleep from selenium.webdriver.common.by import By def test(): driver = webdriver.Chrome("D:/driver/chromedriver.exe") driver.get('http://www.baidu.com') sleep(3) # driver.find_element_by_id('kw').send_keys('selenium') driver.find_element(By.ID,"kw").send_keys("123") driver.find_element_by_id('su').click() sleep(8) driver.quit() if __name__ == '__main__': test();
三、WebDriver 属性及方法
from selenium import webdriver from time import sleep class TestCase(object): def __init__(self): self.driver = webdriver.Chrome(r'D:/driver/chromedriver.exe') self.driver.get('http://www.baidu.com') self.driver.maximize_window() def test_stats(self): print(self.driver.name) #浏览器名称 print(self.driver.current_url) #url print(self.driver.title) #title print(self.driver.window_handles) #句柄 print(self.driver.page_source) #页面源码 self.driver.quit() def test_method(self): self.driver.find_element_by_id('kw').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(2) # 回退 self.driver.back() sleep(2) # 刷新 self.driver.refresh() sleep(2) # 前进 self.driver.forward() sleep(2) # 只关闭当前tab self.driver.close() # 关闭浏览器 self.driver.quit() def test_handles(self): self.driver.find_element_by_link_text('新闻').click() # 获取全部句柄 handles = self.driver.window_handles # 切换到第一个句柄 self.driver.switch_to.window(handles[0]) sleep(2) # 切换到第2个句柄 self.driver.switch_to.window(handles[1]) sleep(2) self.driver.quit() if __name__ == '__main__': case = TestCase() case.test_handles()
四、WebElement 常用属性
from selenium import webdriver class TestCase(object): def __init__(self): self.driver = webdriver.Chrome(r'D:/driver/chromedriver.exe') self.driver.get('https://sahitest.com/demo/linkTest.htm') def test_method(self): e = self.driver.find_element_by_id('t1') # <class 'selenium.webdriver.remote.webelement.WebElement'> print(type(e)) # id 标识 F8BF2C6D76B729DAC7E250BF562EB47C_element_15 print(e.id) # 宽高 {'height': 21, 'width': 737} print(e.size) # 宽高和坐标 {'height': 21, 'width': 737, 'x': 8, 'y': 542.90625} print(e.rect) # 标签名称 input print(e.tag_name) # 文本内容 print(e.text) self.driver.quit(); if __name__ == '__main__': case = TestCase() case.test_method()
五、WebElement 常用方法
def test_method2(self): e = self.driver.find_element_by_id('t1') e.send_keys('test send_keys') print(e.get_attribute('type')) #text print(e.get_attribute('name')) print(e.get_attribute('value')) #test send_keys print(e.value_of_css_property('font')) #13.3333px Arial print(e.value_of_css_property('color')) #rgba(0, 0, 0, 1) e.clear() self.driver.quit();
标签:__,python,selenium,self,driver,语法,test,sleep,print From: https://www.cnblogs.com/xiaozhaoboke/p/17831017.html