0

我正在一個項目,需要位自動化和網絡報廢,我正在使用SeleniumBeautifulSoup(python2.7)硒python多線程

我想開一個網頁瀏覽器的只有一個實例,並登錄到網站,保持該會話,我試圖打開將由線程獨立控制新的標籤,每個線程控制選項卡並執行自己的任務。我應該怎麼做?一個示例代碼會很好。那麼這裏是我的代碼:

def threadFunc(driver, tabId): 
    if tabId == 1: 
     #open a new tab and do something in it 
    elif tabId == 2: 
     #open another new tab with some different link and perform some task 
    .... #other cases 


class tabThreads(threading.Thread): 

    def __init__(self, driver, tabId): 
     threading.Thread.__init__(self) 
     self.tabID = tabId 
     self.driver = driver 

    def run(self): 
     print "Executing tab ", self.tabID 
     threadFunc(self.driver, self.tabID) 

def func(): 
    # Created a main window 

    driver = webdriver.Firefox() 
    driver.get("...someLink...") 

    # This is the part where i am stuck, whether to create threads and send 
    # them the same web-driver to stick with the current session by using the 
    # javascript call "window.open('')" or use a separate for each tab to 
    # operate on individual pages, but that will open a new browser instance 
    # everytime a driver is created 

    thread1 = tabThreads(driver, 1) 
    thread2 = tabThreads(driver, 2) 
    ...... #other threads 

開放的建議使用任何其他模塊,如果需要的話

+0

你能手工做的一樣,同時處理幾個瀏覽器標籤?我想,不是......'Selenium'也不能做到這一點 – Andersson

回答

0

我的理解是,硒驅動程序不是線程安全的。在WebDriver規範中,線程安全部分是空的......我認爲他們沒有解決這個話題。 https://www.w3.org/TR/2012/WD-webdriver-20120710/#thread-safety

因此,儘管您可以共享帶有多個線程的驅動程序引用並從多個線程調用驅動程序,但不能保證驅動程序能夠正確處理多個異步調用。

相反,您必須同步來自多個線程的調用以確保在下次啓動之前完成一個調用,或者您應該只有一個線程進行Selenium API調用......可能處理由多個其他線程填充的隊列中的命令線程。

而且,看到Can Selenium use multi threading in one browser?