【问题标题】:Selenium Perform actions at once like asyncio?Selenium 像异步一样立即执行操作?
【发布时间】:2021-12-02 12:12:34
【问题描述】:

我是新来的,所以请忽略我在描述中犯的一些错误。

好的, 我有一个包含 10 个文本框和 5 个下拉菜单以及 2 个日期和时间的表单。 所以我想立即开始填写所有字段(文本框、下拉菜单和日期),完成所有填写后我必须点击提交按钮。

我想做一些类似 asyncio 的工作。

import asyncio
import time

async def say_after(delay, what):

    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(
        say_after(5, 'hello'))

    task2 = asyncio.create_task(
        say_after(7, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

   print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

我已经尝试过类似线程的方法:

th1 = threading.Thread(target=__func_of_fill_1st_textbox__)
th2 = threading.Thread(target=__func_of_fill_2nd_textbox__)
th3 = threading.Thread(target=__func_of_fill_3rd_textbox__)
th4 = threading.Thread(target=__func_of_fill_4th_textbox__)
th1.start()
th2.start()
th3.start()
th4.start()

但遗憾的是,所有这些都不像 asyncio 那样同时执行。

如果我犯了一些错误,请忽略。

获得了可以理解的答案。

【问题讨论】:

    标签: python multithreading selenium python-asyncio


    【解决方案1】:

    你说你想做一些类似 asyncio 脚本的事情。使用线程相同的输出。

    import threading
    import time
    
    def say_after(delay,what):
        time.sleep(delay)
        print(what)
    
    print(f"started at {time.strftime('%X')}")
    t1 = threading.Thread(target=say_after,args=(5,"hello"))
    t2 = threading.Thread(target=say_after,args=(7,"world"))
    t1.start()
    t2.start()
    
    #join() is what causes the main thread to wait for your thread to finish
    t2.join()
    print(f"finished at {time.strftime('%X')}")
    

    【讨论】:

    • 我认为这对于解决这个问题根本没有用处,尽管它是一个不错的多线程“hello world”示例。
    【解决方案2】:

    问题在于 Selenium 必须与 Web 浏览器引擎进行通信,该引擎会像用户一样加载网页并与之交互:它按顺序执行操作 - 并行化对 Selenium 驱动程序的调用不会成功并行工作。 在设置控件之间可能有一个“延迟”选项,可以提供给 Selenium 驱动程序本身 - 但我不这么认为。

    否则,请检查您是否真的需要 Selenium 来执行此任务(与页面 HTML 本身交互需要它,如果页面元素是使用 javascript 代码动态加载的,则必须) - 如果您只需要向服务器,包含表单数据,您可以使用requests 库来实现,该库很容易与线程并行(或者您可以使用请求的异步等价物)。这种方法一次性将您的数据作为单个结构提交,无需与每个数据字段的任何内容进行交互。 (我认为即使是 Selenium 也可能有一个“发布”选项,可以一次性发送所有数据,而不必填写交互式页面中的所有输入 - 在这里查看:Is there any way to start with a POST request using Selenium?

    如果 Selenium 是您的选择,并且您有几个请求要做,您必须并行化 Selenium 本身:为每个线程启动一个新的 Selenium 驱动程序,而不是为您必须填充的每个控件调用不同线程中的任务,而是调用一次性完成表单填写、提交、响应解析和结果保存的任务——它们并行化这些任务。您可以通过这种方式打开的并行浏览器数量受限于您正在运行脚本的计算机上的硬件资源。 (即,您为每个活动的 selenium 驱动程序创建一个完整的 Web 浏览器)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多