Selenium 可以在一个浏览器中使用多线程吗?

问题描述 投票:0回答:3

我想在多线程中测试网络,但是当我打开太多 chromedriver 时,它们会占用太多内存。我可以在一个浏览器中使用多线程吗?

multithreading selenium selenium-grid2
3个回答
29
投票

WebDriver 不是线程安全的。线程安全问题不在您的代码中,而在实际的浏览器绑定中。他们都假设一次只有一个命令(例如,像一个真正的用户)。但是另一方面,您可以为每个线程实例化一个 WebDriver 实例,但它会启动多个浏览器,这会消耗更多内存。


23
投票

多线程应该在 Webdriver 的不同实例上完成,因为 Webdriver 本身是一个线程。

可以在同一个Webdriver 上运行不同的线程,但是测试的结果将不是你所期望的。让我解释一下。

当您使用多线程在不同的选项卡上运行不同的测试时(这并非不可能,需要一点点编码),您将执行的操作(如单击或发送键)将转到当前聚焦的打开的选项卡,而不管测试运行。这意味着所有测试将在具有焦点的同一个选项卡上同时运行,而不是在预期的选项卡上。

您可以在 Webdriver 中阅读有关多线程的信息。


0
投票

这个页面是几年前创建的,我也有同样的问题,通过谷歌搜索我找不到答案。但最后我可以为此编写代码(绝对不好,因为我不专业。但是它对我有用,所以我写了一个代码方案,也许对搜索和到达此页面的人有帮助)

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
import time

为 Chrome 添加一些不加载图像的设置,等等 _ 我在互联网上找到这些:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--blink-settings=imagesEnabled=false')
options = webdriver.ChromeOptions()
prefs = {'profile.default_content_setting_values':
         {'cookies': 2, 'images': 2, 'javascript': 2,
          'plugins': 2, 'popups': 2, 'geolocation': 2,
          'notifications': 2, 'auto_select_certificate': 2, 'fullscreen': 2,
          'mouselock': 2, 'mixed_script': 2, 'media_stream': 2,
          'media_stream_mic': 2, 'media_stream_camera': 2, 'protocol_handlers': 2,
          'ppapi_broker': 2, 'automatic_downloads': 2, 'midi_sysex': 2,
          'push_messaging': 2, 'ssl_cert_decisions': 2, 'metro_switch_to_desktop': 2,
          'protected_media_identifier': 2, 'app_banner': 2, 'site_engagement': 2,
          'durable_storage': 2}}
options.add_experimental_option('prefs', prefs)
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "none"
#set How much thread you want
thread = 8
#I prefer set a delay. but maybe you want to set it zero.
delay = 0.1
#Luanch Chrome
driver = webdriver.Chrome(desired_capabilities=caps, chrome_options=options)

我使用“books.toscrape.com”作为网址,它有 50 页。

end_page = 50
#create multitabs for our purpose:
for tab in range(thread):
    driver.execute_script("window.open('about:blank','{}');".format(tab))

和刮:

for series, x in enumerate(range(1+end_page//thread)):
    for tab in range(thread):
        driver.switch_to.window(str(tab))
        driver.get(f"https://books.toscrape.com/catalogue/page-{1+tab+series*thread}.html")
        time.sleep(delay)
        if 1+tab+series*thread == end_page: break
    for tab in range(thread):
        driver.switch_to.window(str(tab))
        #Here you can do what you want. for instance:
        Book_boxes = driver.find_elements(By.CLASS_NAME, "product_pod")
        if 1+tab+series*thread == end_page: break
© www.soinside.com 2019 - 2024. All rights reserved.