Selenium+Python [ˈpaɪθən]
0.Selenium安装
pip install selenium
1.打开了浏览器,后边什么都不干了
需要将浏览器驱动放置在环境变量的目录下。
2.打开了浏览器,提示停止以开发者模式运行
原因为浏览器驱动与版本不匹配。
换成相应版本驱动即可,镜像:https://npm.taobao.org/mirrors/chromedriver/
3.一篇写的很详细的博客:http://cuiqingcai.com/2599.html
4.常用函数:
本质上来说这东西目前所知的部分就是模拟一下手工操作,对于常用的测试来说操作大概就这几类:
4.1 选择一个对象
find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
后面的不怎么用,关于xpath,看这里:http://www.w3school.com.cn/xpath/index.asp,麻烦得很。
4.2 对选择的对象搞点事情
element.send_keys() 输入点东西
element.click() 戳一下
Select(element).select_by_visible_text() #from selenium.webdriver.support.ui import Select 选一个值
4.3 其他操作
driver.forward() 浏览器前进
driver.back() 浏览器后退
driver.switch_to_alert().accept() 弹框确定
driver.switch_to_alert().dismiss() 弹框取消
driver.implicitly_wait() 延迟一会,单位为秒
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")) 等待至多一段时间或条件满足
关于选取元素并搞事的部分可以简写一下,省的每次写两行还得新弄一个变量名。
from selenium.webdriver.support.ui import Select def element_input_name(driver,name,text): ele = driver.find_element_by_name(name) ele.send_keys(text) def elements_input_name(driver,name,text,index): ele = driver.find_elements_by_name(name)[index] ele.send_keys(text) def element_click_name(driver,name): ele = driver.find_element_by_name(name) ele.click() def elements_click_name(driver,name,index): ele = driver.find_elements_by_name(name)[index] ele.click() def element_selct_name(driver,name,text): ele = Select(driver.find_element_by_name(name)) ele.select_by_visible_text(text) def elements_selct_name(driver,name,text,index): ele = Select(driver.find_elements_by_name(name))[index] ele.select_by_visible_text(text) def element_input_id(driver,id,text): ele = driver.find_element_by_id(id) ele.send_keys(text) def element_click_id(driver,id): ele = driver.find_element_by_id(id) ele.click() def element_selct_id(driver,id,text): ele = Select(driver.find_element_by_id(id)) ele.select_by_visible_text(text)