如何使用selenium进行多协程填写表单?

系统: win10 环境:python3.7 浏览器:chrom

小白自学phthon,使用selenium写了一个工具,任务是进入帐号,点掉所有被选中的勾选框,但是假设我需要对1000个帐号进行同样的操作,for i in range(len(work)):将会打开1000个浏览器窗口,有没有一种方法能实现每次打开5个窗口,直至遍历帐号列表?
这是我的帐号列表:(假装有1000个帐号)

(https://img-ask.csdn.net/upload/202001/06/1578295823_23416.png)

这是我的代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from gevent import monkey
monkey.patch_all()
from selenium import webdriver
import time, openpyxl, gevent
from  gevent.queue import Queue


work = Queue()


def login():
    if not work.empty():
        user = work.get_nowait()
        driver = webdriver.Chrome()
        driver.get('http://safe.shougang.com.cn/srp/#')
        driver.maximize_window()
# 打开浏览器登陆首安云并最大化窗口
        username = driver.find_element_by_id('userName')
        username.send_keys(user)
        password = driver.find_element_by_id('passWord')
        password.send_keys(user[0][-6:])
# 传入帐号和密码
        button = driver.find_element_by_css_selector('.btn.btn-primary')
        button.click()
        try:
            driver.find_element_by_css_selector('.x-component.x-window-text.x-box-item.x-component-default')
            print('用户%s 密码错误!\n队列剩余%s个' % (user, len(work)))
            driver.close()
            return
        except Exception:
            time.sleep(1)
# 试登陆

        try:
            url_yhpc = driver.find_element_by_partial_link_text('您有待排查')
            url_yhpc.click()
            time.sleep(1)
        except Exception:
            print('用户%s 无隐患排查任务\n队列剩余%s个' % (user, len(work)))
            driver.close()
            time.sleep(1)
            return
        daj_button = driver.find_elements_by_css_selector('.x-grid-checkcolumn.x-grid-checkcolumn-checked')
        for bt in daj_button:
            bt.click()
            time.sleep(0.5)

        send_button = driver.find_element_by_id('button-1302-btnInnerEl')
        send_button.click()
        time.sleep(1)

        yes_button = driver.find_element_by_id('button-1010-btnWrap')
        yes_button.click()
        time.sleep(1)
        driver.close()
        print('用户%s 排查成功\n队列剩余%s个' % (user, len(work)))


def get_users():
    wb = openpyxl.load_workbook(r'C:\users\lz315\Desktop\首安云试验.xlsx')
    ws = wb.active
    for row in ws.rows:
        list_user = []
        for cell in row:
            aa = str(cell.value)
            list_user.append(aa)
        work.put_nowait(list_user)
        wb.close()
    return work
# 读取帐号信息,返回帐号list


start = time.time()
get_users()
task_list = []

for i in range(len(work)):
    task = gevent.spawn(login)
    task_list.append(task)
gevent.joinall(task_list)
end = time.time()
print(end-start)


查看全部
lc825r
午饭天下第一
2020/01/06 15:34
  • python
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复