弹出警报 - 搜索循环

问题描述

我是初学者所以这个问题可能很奇怪:)

我想测试“https://tvn24.pl/”网站的主菜单

我正在寻找元素,我将它们放入列表中,然后遍历它打开找到的每个页面 - 工作正常

现在第二步: 只有两个页面https://kontakt24.tvn24.pl/https://tvn24.pl/)会弹出一个窗口,您应该在其中单击“同意”按钮。

对于每个页面都是完全不同的确认对话框(不同的 xpath、Id 等)

我想写函数(循环) 如果出现窗口,将检查 5 秒钟,如果出现,请单击接受按钮。 我希望此功能可以检查“警报”的两种情况。 如果弹出一个窗口“A” - 点击接受 - 功能结束 如果弹出“B”窗口而不是“A” - 单击接受 - 功能结束 如果没有弹出窗口,什么都不做。

注意:

  1. 这些弹出窗口是覆盖整个页面的元素。
  2. 这些不是警报或框架 - 普通的“DIV”,因此您不能使用 swith 来警报或框架
  3. 我知道,我也可以试试:

有什么提示吗? 用 if 和 elif 循环 while?

我试过这样的东西,但它不起作用

def alert_accept_if_with_Wait_V2(driver):
    V1_alert_window_Id = "onetrust-banner-sdk"
    V1_accept_button_Id = 'onetrust-accept-btn-handler'

    V2_alert_frame_Id = "rodoLayer"
    V2_accept_button_Xpath = './/*[@id="rodoLayer"]//a[@class="rodoFooterBtnAccept"]'

    wait = webdriverwait(driver,timeout=5,poll_frequency=0.5)

    if wait.until(ec.presence_of_element_located((By.ID,V1_alert_window_Id))):
        wait.until(ec.element_to_be_clickable((By.ID,V1_accept_button_Id))).click()
        print(f"On page {driver.current_url} onetrust alert accepted")
    elif wait.until(ec.presence_of_element_located((By.ID,V2_alert_frame_Id))):
        wait.until(ec.element_to_be_clickable((By.ID,V2_accept_button_Xpath))).click()
        print(f"On page {driver.current_url} old alert accepted")
    else:
        print(f"On page {driver.current_url} no alert appeared ")

一个

def alert_accept_if_with_Wait_V1(driver,max_seconds_to_wait=5):

V1 = './/*[@id="onetrust-accept-btn-handler"] '
V2 = './/*[@id="rodoLayer"]//a[@class="rodoFooterBtnAccept"]'

seconds = 0
while range(max_seconds_to_wait):
    if driver.find_element_by_xpath(V1 or V2):
        driver.find_element_by_xpath(V1 or V2).click()
        return False
    else:
        seconds += 1
    time.sleep(1)
else:
    print(f"On page {driver.current_url} no alert appeared ")

解决方法

seconds = 0
while seconds < 3:
    V1 = driver.find_elements_by_xpath('.//*[@id="onetrust-accept-btn-handler"]')
    V2 = driver.find_elements_by_xpath('.//*[@id="rodoLayer"]//a[@class="rodoFooterBtnAccept"]')
    if len(V1) > 0:
        V1[0].click()
        print(f"On page {driver.current_url} onetrust alert accepted")
        return False
    elif len(V2):
        V2[0].click()
        print(f"On page {driver.current_url} old alert appeared")
        return False
    else:
        seconds += 1
        time.sleep(1)
else:
    print(f"On page {driver.current_url} no alert appeared ")
    return False