一.为了解决繁琐、重复的操作步骤,然机器代替人来做
准备:python 3.6 +selenium + chromedriver2.35
chromedriver 要兼容本地的chrome
对应版本号 https://chromedriver.storage./2.36/notes.txt
ChromeDriver |
Chrome |
v2.36 |
v64-66 |
v2.35 |
v63-65 |
v2.34 |
v61-63 |
v2.33 |
v60-62 |
v2.32 |
v59-61 |
v2.31 |
v58-60 |
v2.30 |
v57-60 |
chromedriver2.3.5 下载地址 :https://chromedriver.storage./index.html?path=2.35/
selenium 安装 pip install selenium
二.代码实现
方式一: 直接调用浏览器模拟人工操作(可视化操作)
# encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
# 前台开启浏览器模式
def openChrome():
# 加启动配置
option = webdriver.ChromeOptions()
option.add_argument('disable-infobars')
# 打开chrome浏览器
driver = webdriver.Chrome(chrome_options=option)
return drivers
# 授权操作
def operationAuth(driver):
url = "http://www.baidu.com"
driver.get(url)
# 找到输入框并输入查询内容
elem = driver.find_element_by_id("kw")
elem.send_keys("selenium")
# 提交表单
driver.find_element_by_xpath("//*[@id='su']").click()
print('查询操作完毕!')
# 方法主入口
if __name__ == '__main__':
# 加启动配置
driver = openChrome()
operationAuth(driver)
方式二: 后台模拟浏览器操作(不显示浏览器,省去浏览器启动的时间)
需要先下载 selenium3.9.1 jar 本地需要java环境(对应的版本为jdk1.8)
下载地址:https:///GrGHyQ
启动seleniumjar 命令 java -jar selenium-server-standalone.jar -port 3456
控制台查看是否启动成功(此方法全部为后台操作,为了节省操作时间而不会真的调用浏览器进行操作)
baseUrl = "http://192.168.3.44:9000"
# 无需启动浏览器模式
def openChromBack():
return webdriver.Remote(command_executor="[http://localhost:4567/wd/hub](http://localhost:4567/wd/hub "selenium 本地测试地址")",
desired_capabilities=DesiredCapabilities.HTMLUNIT)
# 授权操作
def operationAuth(driver, mobile, inMobile):
url = baseUrl + '/front/account/direcTrfAuth?userName=' + str(mobile)
driver.get(url)
# 获取checkbox并勾选
driver.find_element_by_xpath("//*[@id='Agreement1']").click()
driver.find_element_by_xpath("//*[@id='Agreement2']").click()
# 找到密码输入框并输入密码
elem = driver.find_element_by_id("TransPwd")
elem.send_keys(123456)
# 提交表单
driver.find_element_by_xpath("//*[@id='submit']").click()
print('授权用户:' + mobile + '完成授权操作!')
if __name__ == '__main__':
# 获取浏览器驱动
driver = openChromBack()
mobiles = 18888888888
operationAuth(driver, str(mobile), str(inMobile))
页面操作效果图(只是为了查看页面的效果,要显示浏览器需要调用webdriver.Chrome方法)
|