簡體   English   中英

如何使用selenium處理定時彈出窗口?

[英]How to handle timed popups using selenium?

我無法找到有關如何正確處理定時彈出窗口的任何指南。 我的目標是關閉一個彈出窗口,因為它會在打開時將selenium與網站進行交互。 最大的問題是,每次打開網站時彈出窗口的時間都不一樣,它會有所不同。

我已經嘗試在代碼中插入一個簡單的'try'方法到彈出窗口時執行代碼的地方,但是由於變量彈出時序而無法正常工作。

def pop_up_off(self):
    try:
        self.driver.find_element_by_css_selector('a_css_selector').click()
        sleep(.5)
    except Exception:
        pass

預期的結果是擺脫與正在進行的selenium腳本中斷的可變定時彈出窗口。

使用While循環和WebdriverWait提到timeoutpoll_frequency來檢查元素的存在,如果它會點擊元素並打破循環,否則繼續upout.Hope這有幫助。

while(True):
  elements=WebDriverWait(self.driver, 300,1 ).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'a_css_selector')))
  if(len(elements)>0):
      self.driver.find_element_by_css_selector('a_css_selector').click()
      break
  else:
    continue

請注意:您需要使用以下導入。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

EDITED

while(True):
  elements=driver.find_elements_by_css_selector('a_css_selector')
  if(len(elements)>0):
      self.driver.find_element_by_css_selector('a_css_selector').click()
      break
  else:
    continue

你應該明確地等待這種情況。 它將等待給定的條件實現,不再需要。 顯式等待每半秒檢查一次。 如果條件在給定時間內不滿足,則會拋出超時異常。

嘗試這個:

WebDriverWait(driver,30).until(EC.presence_of_element_located((By.CSS_SELECTOR,"a_css_selector"))).click()

要使用顯式等待,您必須導入以下內容

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

如果您不想等待測試開始時的彈出窗口,也許創建一個與您的測試一起運行的后台線程就可以了。

import threading

trigger = True #if this trigger is set to False, the thread stops running.

def pop_up_off(self):
    while trigger == True:
        try:
            self.driver.find_element_by_css_selector('a_css_selector').click()
            trigger = False
        except Exception:
            pass

-

def test(your args):
    #your test before the popup page is opened...
    close_popup = threading.Thread(target=pop_up_off, args= your args)
    close_popup.start()
    #your test after the popup page is opened...

這不會讓你的測試等待彈出窗口看起來繼續,它將嘗試在測試運行時檢測並關閉彈出窗口

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM