在Python中使用Selenium阻止/延迟模式对话框关闭

2024-05-16 16:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试检索网站上每个页面的页面名称。步骤如下:

  1. 单击设置图标

    • 出现一个模态对话框(我认为这就是它们的名称?)。对话框在关闭前显示三秒钟。你知道吗
  2. 点击“重命名页面”

    • 弹出窗口显示一个文本字段(包含页面名称)。弹出窗口还包含按钮“确定”和“取消”
  3. 在文本字段中检索名称

  4. 按“确定”

  5. 转到下一页。重复步骤1-4

出于某种原因,在第2阶段,我收到了一个TimeOutException错误,这似乎是随机的。我说是随机的,因为错误有时发生在第55页,有时发生在第130页,以此类推。我相信这可能是因为对话框关闭,在重命名页面按钮被点击之前(这很奇怪,因为3秒应该是足够的时间来点击按钮)。你知道吗

Screenshot

我正在使用Spyder框架来编写代码。当TimeOutException发生时,如果我运行步骤1中的代码。一切正常。所以出于某种原因,有时会出现错误,有时不会。你知道吗

设置图标的HTML代码如下:

<div 
id="_labsfluxbar_WAR_labsfluxbarportlet_showCurrentPageSettingsPopupButton" 
class="labs-fluxbar-portlet-current-page-settings-popup">
</div>

“重命名页面”的HTML代码

<ul 
class="labs-fluxbar-portlet-page-menu-items">   
    <li class="labs-fluxbar-portlet-page-menu-item labs-fluxbar-portlet-page-menu-item-rename" title="Rename this page" 
onclick="_labsfluxbar_WAR_labsfluxbarportlet_renamePage('9398653')">    Rename page
</li>

Python中的代码:

i = 0
while True:
    #Get page name
    # Step 1 - Click on Settings icon
    settings = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "_labsfluxbar_WAR_labsfluxbarportlet_showCurrentPageSettingsPopupButton"))) #Search for settings button
    settings.click() #click settings icon
    # Step 2 - Click on the "Rename Page" button
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='labs-fluxbar-portlet-current-page-settings-popup-content']//li[@title='Rename this page']"))).click() #Click on the Rename page element 
    # Step 3 - Retrieve page name from text field
    page = driver.find_element_by_xpath("//input[@id='popup_prompt']") 
    page_name = page.get_property("value") #Copy the name of page
    print(page_name)
    # Step 4 - Click ok to close PopUp window
    driver.find_element_by_xpath("//input[@id='popup_ok']").click() #Exit the popup window
    # Step 5- Go to the next page
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "_labsfluxbar_WAR_labsfluxbarportlet_pageDropdownList")))
    select = Select(driver.find_element_by_id('_labsfluxbar_WAR_labsfluxbarportlet_pageDropdownList'))
    select.select_by_index(i)
    i += 1

TimeoutException(有时)发生在运行以下行之后,但是我不明白为什么?你知道吗

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='labs-fluxbar-portlet-current-page-settings-popup-content']//li[@title='Ange ett nytt namn för sidan']"))).click()

有没有人对发生了什么有什么建议,或者可以采取什么措施来预防?你知道吗


Tags: to代码settingsdriverpage页面elementportlet