【问题标题】:Run other commands alongside selenium与 selenium 一起运行其他命令
【发布时间】:2021-11-07 15:08:52
【问题描述】:

我目前正在尝试制作一个启动 selenium 线程的不和谐机器人。它可以工作,但唯一的问题是,如果 selenium 花费太长时间,我将无法使用其他命令。它最终会响应下一个命令,但只有在 selenium 完成后才会响应。

这就是我所拥有的:

import threading
import discord
import time
from selenium import webdriver
from discord.ext import tasks, commands

client = commands.Bot(command_prefix='!')

def start(url):
    driver = webdriver.Firefox()
    driver.get(url)
    time.sleep(10)
    driver.close()

@client.command()
async def rq(ctx):
    #if link == None:
        #await ctx.send("Please send a link!")
    await ctx.send("Started!")
    threading(target=start("https://google.com/")).start()

@client.command()
async def sc(ctx):
    await ctx.send("some command")

if __name__ == "__main__":
    client.run(token)

任何解决方案都会有所帮助!

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: python python-3.x selenium discord discord.py


【解决方案1】:

你调用线程的方式不对:

threading(target=start("https://google.com/")).start()

这是做什么的:

  1. 在主线程上调用 start 函数,将 URL 传递给它。
  2. 等待函数完成。
  3. 获取返回值 (None) 并将其作为 target 函数传递给线程构造函数(顺便说一下,我想你的意思是 threading.Thread)。

所以当线程启动时,实际工作已经在主线程上完成了,线程本身什么也不做。

启动线程并传递一些参数的正确方法是:

threading.Thread(target=start, args=("https://google.com/",)).start()

注意start 后面没有跟(),所以我们不直接调用函数;我们将函数 itself 传递给 Thread 构造函数。参数作为 args 参数的元组给出(因此是尾随逗号)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2021-06-06
    相关资源
    最近更新 更多