一.对话框:
例:点击百度的登录,弹出的小窗口
#coding=utf-8from selenium import webdriverfrom time import sleepdr=webdriver.Chrome()dr.get("http://www.baidu.com")#一定要记得设置等待时间,要不然定位不到!!!dr.find_element_by_link_text("登录").click()sleep(3)#思路:二次定位,点击登录后,定位登录的弹出框,用id或class_name都可以!!然后定位登录框的姓名输入框#login=dr.find_element_by_id("TANGRAM__PSP_8__userName") 直接定位,定位不到!!!!!#login=dr.find_element_by_class_name("tang-content").find_element_by_name("userName")login=dr.find_element_by_id("TANGRAM__PSP_8__form").find_element_by_id("TANGRAM__PSP_8__userName")login.send_keys("17710192039")dr.find_element_by_name("password").send_keys("a7s5dfg!")dr.find_element_by_id("TANGRAM__PSP_8__submit").submit()
二.多窗口,从一个页面跳转到另外一个页面
思路:先定位百度登录的句柄,然后跳转到注册页面,点击转到非登录页面的句柄!!!!!
#coding=utf-8from selenium import webdriverfrom time import sleepdr=webdriver.Chrome()dr.get("http://passport.baidu.com")#一定要记得设置等待时间,要不然定位不到!!!nowhandle=dr.current_window_handleallhandles0=dr.window_handles#当前登录页面只有一个句柄print "现在是登录页面"print nowhandlefor h in allhandles0: print h#跳转到注册页面一共有两个句柄(包含登录页面的)print "现在进入注册页面"dr.find_element_by_link_text("立即注册").click()sleep(3)allhandles=dr.window_handlesfor handle in allhandles: print handlefor handle in allhandles: if handle!=nowhandle: dr.switch_to_window(handle)sleep(3)#关闭当前窗口dr.close()#转到登录首页dr.switch_to_window(nowhandle)
三.弹出框处理 alert:使用switch_to_alert() (accept,dismiss,send_keys)
#coding=utf-8from selenium import webdriverfrom selenium.webdriver.common.action_chains import ActionChainsfrom time import sleepdr=webdriver.Chrome()dr.get("http://www.baidu.com")#此处为百度页面的设置,涉及下拉框的处理!!!处理思路:一般是两次点击,一次点击弹出下拉框,另一次点击选项,如果是鼠标移动上弹出的用 move_to_element()#先定位到“设置”dr.find_element_by_link_text("设置").click()sleep(3)sou=dr.find_element_by_class_name("pf")sou.click()#ActionChains(dr).move_to_element(sou).perform() 这种的一般用于找父元素,下拉框.子元素,移动到子元素上sleep(3)#点击“确定”,用accept()dr.switch_to_alert().accept()#点击取消",用dismiss()dr.switch_to_alert().dismiss()#输入内容,直接用send_keys()dr.switch_to_alert().send_keys()#输出内容print dr.switch_to_alert().text
四.上传文件,直接定位点击按钮,并send_keys即可(路径必须正确)
upload.html
<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8" /><title>upload_file</title><link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" /></head><body> <div class="row-fluid"> <div class="span6 well"> <h3>upload_file</h3> <input type="file" name="file" /> </div> </div></body><script src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script></html>
uoload.py
#coding=utf-8from selenium import webdriverfrom time import sleepimport osdr=webdriver.Chrome()#打开上传文件的页面file_path='file:///'+os.path.abspath('upload.html')dr.get(file_path)sleep(3)#点击”选择文件“按钮,dr.find_element_by_name("file").send_keys('D:\\zhihu.cookie.txt')sleep(3)
效果如下: