selenium模块

一、基础知识

1 基础

official::Selenium 浏览器自动化项目 | Selenium

API:键鼠操作

驱动下载:

等待

  • 隐式等待

  • driver.implicitly_wait(time_to_wait=10)(界面全部加载完成后才会向下执行代码,超出时间则抛出异常)

2 使用驱动

# 使用驱动
from selenium.webdriver.chrome.service import Service
ser = Service(r"./chromedriver.exe")
bro = webdriver.Chrome(service = ser)

3 简单使用

# 简单使用
from selenium import webdriver

# 打开浏览器
driver = webdriver.Chrome()
# 打开的网址
driver.get(" ")
# 获得源码
text = driver.page_source


from selenium.webdriver.common.by import By
# 通过元素找标签,元素选择在 By 类中
input_tag = driver.find_element(by,value)
# 设置标签值
input_tag.send_keys()


from selenium.webdriver.common.keys import Keys # 键盘操作
# 键盘操作
send_keys( Keys.ENTER )


from selenium.webdriver.common.action_chains import ActionChains # 鼠标操作
# 鼠标操作
ActionChains(driver).click(input_tag).perform()
# 左键单击
input_tag.click()


# 回退
driver.back()
# 前进
driver.forward()
#退出
driver.quit()

4 定位

# 定位位置
# 切换定位到指定 id 的 iframe 中
iframe:driver.switch_to.frame('id')

# 浏览器中元素中的某一点定位
ActionChains(bro).move_to_element_with_offset(tag,x,y).click().perform()

5 其他设置

# 无头浏览器(无界面显示)
from selenium.webdriver.chrome.options import Options

op = Options()
op.add_argument('--headless')
op.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=op)

# 老版防检测(不一定有效)
op = Options()
op.add_experimental_option('excludeSwitches',['enable-automation'])
driver = webdriver.Chrome(options=op)

6 鼠标高级操作

# 拖动
action = ActionChains(driver)
action.click_and_hold(tag) # 按住
for i in range(num) :
action.move_by_offset(x,y).perform() # 位移
action.release() # 释放动作链

7 其他操作

# 浏览器
# 整张截图存入 png 中
driver.save_screenshot(".png")

# 组件
# 左上角的坐标(字典key为 x , y)
tag.location
# 大小(字典key为 x , y)
tag.size:

二、 图片处理

1 使用Image

from PIL import Image

# 读取path中图片
im = Image.open(path)
# 指定范围裁剪(tuple:( 左上x,左上y,右下x,右下y))
res = im.crop(tuple)
# 存入到path中
res.save(path)