本文共 987 字,大约阅读时间需要 3 分钟。
selenium自动化测试工具可以模拟人的部分操作,包括点击、拖动和填写等,用起来很方便。但它并不是万能的,而且现在selenium对模态对话框的处理还不是很完善。当然,对于一些简单的弹框,还是有方法处理的。
比如下面这种:
driver.find_element_by_xpath(login_button).click() # 点击登录while True: # 直到输入正确的验证码以后,才继续后续流程 try: driver.switch_to.alert.accept() # 点击确定按钮 # switch_to_alert() --定位弹出对话框 # text() --获取对话框文本值 # accept() --相当于点击“确认” # dismiss() --相当于点击“取消” # send_keys() --输入值(如果有输入对话框) except NoAlertPresentException: # 没有弹窗,说明验证码输入正确,退出循环 break else: print("请在网页重新输入正确的验证码!") time.sleep(LONG_PROTECTION_TIME / 2) # 等待重新输入正确的验证码 driver.find_element_by_xpath(login_button).click() # 点击登录
但是如果碰到下面这种,就没那么容易处理了:
这种弹窗属于浏览器的一些插件, 用F12也无法定位弹窗里边的元素。虽然selenium也有按照坐标进行点击的功能,但让selenium按照坐标自动去点击弹窗里边的东西就更困难了,而且还涉及到文本框的填写等。
这个时候,就是该用 time.sleep()的时候了,留出足够长的等待时间,让人工手动对弹窗进行处理,只要保证selenium在进行下一步操作之前把弹框给点掉,后续流程就可以继续正常运行。当然,人的操作不能与selenium中的程序处理操作相冲突,不能对selenium的后续处理逻辑造成影响。
转载地址:http://fdjqi.baihongyu.com/