Web自动化测试利器 - Selenium

这个三方库太强大了,可以对浏览器做各种自动化的操作,自动化测试,当然用它来写爬虫当然是更加强悍。

官方文档:http://selenium-python.readthedocs.io/index.html

Selenium有很强大的页面交互能力

比如点击,输入等等。前提就是要找到页面中的元素。WebDriver提供了各种方法来寻找元素。例如下面有一个表单输入框。

安装

pip install selenium

示例1 - 获取指定元素

<input type="text" name="passwd" id="passwd-id" />

我们可以这样获取它:

element = driver.find_element_by_id("passwd-id")

element = driver.find_element_by_name("passwd")

element = driver.find_elements_by_tag_name("input")

element = driver.find_element_by_xpath("//input[@id='passwd-id']")

示例2 - 自动登录并点击菜单

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
chrome_driver = r"C:\chrome\chromedriver.exe"  # 该文件需要和本机chrome浏览器版本匹配
# 隐藏浏览器界面
option = Options()
option.add_argument('--headless')
chrome = webdriver.Chrome(executable_path=chrome_driver, options=option)

# 显示浏览器界面
# chrome = webdriver.Chrome(executable_path=chrome_driver)

# 开始登陆url
chrome.get(url)
chrome.implicitly_wait(2)

# 自动跳过SSL证书不信任
try:
    details_button = chrome.find_element_by_id("details-button")
    details_button.click()
    time.sleep(1)
    proceed_link = chrome.find_element_by_id("proceed-link")
    proceed_link.click()
    time.sleep(1)
except Exception as e:
    print(e)

# 自动输入用户名和密码
chrome.find_element_by_id("username").send_keys(username)
chrome.find_element_by_id("password").send_keys(password)

# 点击登录
chrome.find_element_by_id("login").click()
time.sleep(1)

# 点击Settings按钮
try:
    chrome.find_element_by_id("Settings").click()
    time.sleep(1)
except Exception as e:
    chrome.find_element_by_id("settings").click()
    time.sleep(1)


# 点击确认对话框
chrome.switch_to.alert.accept()
time.sleep(2)

# 关闭浏览器
chrome.close()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值