本文共 1091 字,大约阅读时间需要 3 分钟。
selenium 可以使用 driver.execute_script(js) 来执行部分JS代码。虽然 selenium 自动化测试工具本质上是模拟人的部分操作,但是它所具备的功能让他可以突破人的极限去做一些事情,甚至可以做到一些连人都做不到的事情。
比如说在验证码输入错误以后,给出用户重新输入的提示信息:
driver.find_element_by_xpath(login_button).click() # 点击登录time.sleep(SHORT_PROTECTION_TIME) # 等待片刻再去点击弹窗确认按钮while True: try: driver.switch_to.alert.accept() # 试图点击弹窗 except NoAlertPresentException: break # 没有弹窗,表示验证码输入正确,退出循环 else: # 有弹窗并已经点掉,则给出提示并等待重新输入验证码 print("请在网页重新输入正确的验证码!") js = """ var span = document.createElement('span'); span.innerHTML = '请在10秒内重新输入正确的验证码!'; span.style.position = 'absolute'; span.style.top = '49%'; span.style.left = '47%'; span.style.color = 'red'; span.style.fontSize = '20px'; document.body.appendChild(span); setTimeout(function() {document.body.removeChild(span)},9000); """ driver.execute_script(js) time.sleep(LONG_PROTECTION_TIME / 2) # 等待重新输入验证码 driver.find_element_by_xpath(login_button).click() # 点击登录 time.sleep(SHORT_PROTECTION_TIME) # 等待片刻再去点击弹窗确认按钮
转载地址:http://bdjqi.baihongyu.com/