admin 管理员组

文章数量: 887016

在运行自动化脚本的时候,难免遇到各种情况,近日贫僧遇到很操蛋的情况,在加载url的时候需要输入用户名,密码,截图如下,看到这样的弹框第一反应就是用driver.switch_to_alert(),然后调用send_keys(),appept(),但是发现并没有卵用

初次脚本如下:

username = u'ranzhi'
password = u'ranzhi'
driver = webdriver.Chrome()
driver.maximize_window()
print ('111')
driver.get('http://127.0.0.1')
print ('222')
alert = driver.switch_to_alert()
alert.send_keys(username)
alert.send_keys(password)
time.sleep(2)
alert.accept()
driver.quit()

运行之后发现没用,url仍然加载不完全,不能进行下一步操作,即指定打印111,无法运行到打印222的位置,贫僧继续网上查资料,即driver.set_page_load_timeout(),设置超时事件,代码如下

 

username = u'ranzhi'
password = u'V>rLayxoMba'
driver = webdriver.Chrome()
driver.maximize_window()
driver.set_page_load_timeout(10)
print('111')
try:
    driver.get('http://127.0.0.1')
except:
    pass
print('222')
time.sleep(2)
driver.quit()

运行后发现还是没用,抛出错timeout后,浏览器加载的url会被回退,导致启动的浏览器没有加载的url,最后使多线程+python加键盘事件搞定

脚本思路:开启第一个线程启动浏览器,打开待操作的页面,页面进入输入用户名,密码,当前页面的输入焦点为用户名输入框,当前再启动第二个线程,调用python键盘事件,对输入框进入输入,然后通过tab以及enter完成用户名,密码输入并登陆完成

#coding=utf-8
'''
Created on 2018年12月1日

@author: yangkai
'''
import threading 
from selenium import webdriver
import time
import win32api,win32con


def web():
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get('http://127.0.0.1')

def pyr():
    time.sleep(7)
    for i in 'ranzhi':
        oneKey(i)
    oneKey('ENTER')
    time.sleep(2)
    oneKey('TAB')
    time.sleep(2)
    for i in 'ranzhi':
        oneKey(i)
    oneKey('ENTER')
    oneKey('ENTER')
    time.sleep(5)


def oneKey(key):
    keyboard = {'*':'106','+':'107','-':'109','.':'110','/':'111','F1':'112','F2':'113','F3':'114','F4':'115','F5':'116','F6':'117','F7':'118','F8':'119','F9':'120','F10':'121','F11':'122','F12':'123','A':'65','B':'66','C':'67','D':'68','E':'69','F':'70','G':'71','H':'72','I':'73','J':'74','K':'75','L':'76','M':'77','N':'78','O':'79','P':'80','Q':'81','R':'82','S':'83','T':'84','U':'85','V':'86','W':'87','X':'88','Y':'89','Z':'90','0':'48','1':'49','2':'50','3':'51','4':'52','5':'53','6':'54','7':'55','8':'56','9':'57','BACKSPACE':'8','TAB':'9','CLEAR':'12','ENTER':'13','SHIFT':'16','CTRL':'17','ALT':'18','CAPSLOCK':'20','ESC':'27','SPACEBAR':'32','PAGEUP':'33','PAGEDOWN':'34','END':'35','LEFT':'37','UP':'38','HOME':'36','RIGHT':'39','DOWN':'40','INSERT':'45','DELETE':'46','HELP':'47','NUMLOCK':'144'}
    key = key.upper()
    win32api.keybd_event(int(keyboard[key]),0,0,0)
    win32api.keybd_event(int(keyboard[key]),0,win32con.KEYEVENTF_KEYUP,0)

threads = []
t1 = threading.Thread(target=web)
t2 = threading.Thread(target=pyr)
threads.append(t1)
threads.append(t2)
threads[0].start()
threads[1].start()
threads[0].join()
threads[1].join()

 

本文标签: 多线程 账号 加载 密码 selenium