selenium 自动化测试初探(PC——chrome)

一、环境准备:

windows10 python3 selenium

pip install selenium

chrome 驱动下载根据浏览器版本选择 https://npm.taobao.org/mirrors/chromedriver 

二、相关方法

单个元素定位方法

  • find_element_by_id()
  • find_element_by_name()
  • find_element_by_class_name()
  • find_element_by_tag_name()
  • find_element_by_link_text()
  • find_element_by_partial_link_text()
  • find_element_by_xpath()
  • find_element_by_css_selector()

多个元素定位:

  • find_elements_by_id()
  • find_elements_by_name()
  • find_elements_by_class_name()
  • find_elements_by_tag_name()
  • find_elements_by_link_text()
  • find_elements_by_partial_link_text()
  • find_elements_by_xpath()
  • find_elements_by_css_selector()

driver.refresh() 刷新

clear(): 清除文本。

send_keys (value): 模拟按键输入。

click(): 单击元素。

submit() 提交

窗口切换

  • current_window_handle:获得当前窗口句柄。
  • window_handles:返回所有窗口的句柄到当前会话。
  • switch_to.window():用于切换到相应的窗口,与上一节的switch_to.frame()类似,前者用于不同窗口的切换,后者用于不同表单之间的切换

三、例子解析

例子:登陆v2ex 网站,验证码问题需解决

#coding:utf-8
from selenium import webdriver
driver=webdriver.Chrome()
driver.get('https://www.v2ex.com/')
driver.find_element_by_link_text("登录").click()
username=driver.find_element_by_css_selector("#Main > div.box > div.cell > form > table > tbody > tr:nth-child(1) > td:nth-child(2) > input")
username.send_keys('test')
passwd=driver.find_element_by_css_selector("#Main > div.box > div.cell > form > table > tbody > tr:nth-child(2) > td:nth-child(2) > input")
passwd.send_keys('11111')
captcha=driver.find_element_by_css_selector("#Main > div.box > div.cell > form > table > tbody > tr:nth-child(3) > td:nth-child(2) > input")
captcha.send_keys('dddd')
captcha.submit()

四、总结

环境安装简便,操作简单,容易上手。

猜你喜欢

转载自www.cnblogs.com/maoxianfei/p/9775926.html