一、web自动化定位
- 配置环境
1. Firefox
2. 三个插件 - 使用
1. Xpath
2. css选择器
二、selenium使用
1.环境搭建
Python3.7-3.9
Firefox35
selenium=2.48.0
三、selenium对浏览器操作
from selenium import webdriver
drvier = webdriver.FireFox()
drvier = webdriver.Chrome()
driver.get(url)
driver.maximize_window()
driver.get_window_size()
driver.set_window_size(w,h)
driver.get_window_position()
driver.set_window_position(x,y)
driver.back()
driver.forword()
driver.current_url
driver.title
driver.page_source
data = driver.get_screenshot_as_png()
with open('a.png','wb') as f:
f.write(data)
driver.get_screenshot_as_file('b.png')
driver.close()
driver.quit()
四、两类、八大元素定位方法
from selenium.webdriver.common.by import By
id
ele = driver.find_element_by_id('id')
ele = driver.find_element(By.ID,'id')name
ele = driver.find_element_by_name('name')
ele = driver.find_element(By.NAME,'id')class
ele = driver.find_element_by_class_name('class')
ele = driver.find_element(By.CLASS_NAME,'class')Xpath
ele = driver.find_element_by_xpath('xclass')
ele = driver.find_element(By.XPATH,'xclass')css selector
ele = driver.find_element_by_css_selector("#id .class")
ele = driver.find_element(By.CSS_SELECTOR,'#id .class')link_text
ele = driver.find_element_by_link_text("text")
ele = driver.find_element(By.LINK_TEXT,'text')partial_link_text
ele = driver.find_element_by_partial_link_text("text")
ele = driver.find_element(By.PARTIAL_LINK_TEXT,'text')table name,标签名必须唯一
ele = driver.find_element_by_tag_name("TAG_NAME")
ele = driver.find_element(By.TAG_NAME,'"TAG_NAME"')
五、元素的操作
ele.click()
ele.clear()
ele.send_keys("值")
ele.submit()
六、鼠标和键盘
鼠标
from selenium.webdriver import ActionoChains
ActionChains(driver).context_click(ele).perform()
ActionChains(driver).double_click(ele).perform()
ActionChains(driver).move_to_element(ele).perform()
键盘
from selenium.webdriver.common.keys import Keys
send_keys(Keys.BACK_SPACE) 删除键(BackSpace)
send_keys(Keys.SPACE) 空格键(Space)
send_keys(Keys.TAB) 制表键(Tab)
send_keys(Keys.ESCAPE) 回退键(Esc)
send_keys(Keys.ENTER) 回车键(Enter)
send_keys(Keys.CONTROL,'a') 全选(Ctrl+A)
send_keys(Keys.CONTROL,'a') 全选(Ctrl+A)
send_keys(Keys.CONTROL,'x') 剪切(Ctrl+X)
send_keys(Keys.CONTROL,'v') 粘贴(Ctrl+V)
send_keys(Keys.F1) 键盘 F1
send_keys(Keys.F12) 键盘 F12
七、浏览器等待
-
固定等待:硬等指定的时间
```python import time time.sleep(3) ```
-
显示等待
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver WebDriverWait(driver, 3, 0.5, ignored_exceptions=None).until(EC.presence_of_element_located(By.ID, 'kw'))
-
隐式等待
driver.implicitly_wait(10)