我在python工作过selenium。我想使程序多线程(4-10个线程),但它不能工作。我也不知道原因。
启动时:输出:线程启动!
应该发生什么:输出:线程启动了!线程启动了!线程启动了!线程启动了!线开始了!..。
以下是我尝试过的:
from selenium import webdriver
import string
import random
import time
from threading import Thread
def bot():
while True:
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging']) # Disables logging
options.add_argument('--disable-extensions')
options.add_argument('--profile-directory=Default')
options.add_argument("--incognito")
options.add_argument("--disable-plugins-discovery");
options.add_argument("--headless") # Turns Chrome into headless browser
options.add_argument("--mute-audio")
driver = webdriver.Chrome(options=options)
driver.get("https://example.com/")
driver.close()
def main():
for _ in range(10):
print("Thread started!")
worker = Thread(target=bot())
worker.setDaemon(True)
worker.start()
if __name__ == '__main__':
main()发布于 2021-01-08 21:14:23
你有三个问题。首先,你说:
worker = Thread(target=bot())它应该是:
worker = Thread(target=bot)第二个问题是下面一行:
worker.setDaemon(True)你能说出你为什么这么做吗?守护进程线程是在所有非守护进程线程终止后立即自动终止的线程。您有一个非守护进程线程,即在函数main()中启动所有这些守护进程线程的主线程。一旦main返回(在启动所有这些dameon线程之后),它就会终止!因此,所有守护进程线程都会随之结束。这就是你需要的:
def main():
threads = [Thread(target=bot) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join() # wait for this thread to terminate第三个问题是函数bot。
driver.close()应:
driver.quit()不仅关闭窗口,而且终止进程并允许线程终止。
发布于 2021-01-08 21:03:36
您尝试过删除while True函数中的bot()吗?线程意味着主程序多次执行您的辅助功能。
https://stackoverflow.com/questions/65636226
复制相似问题