所以我正在尝试同时打开一系列网络浏览器。当我调用单个类实例时,我这样做没有问题(如果它是对象的实例,请纠正我(。 我正在尝试使我的代码更漂亮,并通过 for 循环将参数提供给实例。浏览器打开正常,但随后它们都消失了。有人告诉我这与垃圾收集有关,但不确定如何解决它。请帮忙。
from selenium import webdriver
from threading import Thread
class Dashboard(Thread):
def __init__(self, position, url):
super().__init__()
self.position = position
self.url = url
def run(self):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--window-size=256,160')
#chrome_options.add_argument('--start-maximized')
chrome_options.add_argument(self.position)
self.driver = webdriver.Chrome(options=chrome_options)
self.driver.get(self.url)
pos = ['--window-position=100,100', '--window-position=1000,1000']
web = ['https://www.youtube.com', 'https://www.facebook.com']
for a, b in zip(pos, web):
screen = Dashboard(a, b).start()
驱动程序超出范围,导致浏览器关闭。将驱动程序添加到某个全局变量。
from selenium import webdriver
from threading import Thread
all_drivers = []
class Dashboard(Thread):
def __init__(self, position, url):
super().__init__()
self.position = position
self.url = url
self.driver = None
def run(self):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--window-size=256,160')
# chrome_options.add_argument('--start-maximized')
chrome_options.add_argument(self.position)
self.driver = webdriver.Chrome(options=chrome_options)
self.driver.get(self.url)
all_drivers.append(self.driver)
pos = ['--window-position=100,100', '--window-position=1000,1000']
web = ['https://www.youtube.com', 'https://www.facebook.com']
for a, b in zip(pos, web):
screen = Dashboard(a, b).start()
# close the drivers once your purpose is solved
for driver in all_drivers:
driver.quit()