【问题标题】:Not implicit waiting for new element after clicking单击后不隐式等待新元素
【发布时间】:2017-08-25 13:56:00
【问题描述】:

我只是想知道是否有更可靠的方法来等待元素,或者它是否只是一个顽固的页面。我对 Python Selenium 还很陌生,但我注意到没有下面的睡眠等待 https://casino.bovada.lv/(它现在是灰色的)命令 Selenium 单击扑克选项卡,然后在页面正确加载之前它单击马的选项卡,此单击确实没有什么。我可以使用睡眠等待命令,但有点违背了等待元素出现的目的。

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

driver = webdriver.Chrome(executable_path=r'C:\Brother\chromedriver.exe')
driver.set_window_size(1024, 600)
driver.maximize_window()
driver.get("https://sports.bovada.lv/soccer")

time.sleep( 4 )

element = WebDriverWait(driver, 20000).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#ui-app-primary-menu > a.primary-menu_item.channel-poker.channel.channel-poker.ng-isolate-scope > span")));

element.click();

driver.get("https://casino.bovada.lv/")
#time.sleep( 4 )
element = WebDriverWait(driver, 20000).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#ui-app-primary-menu > a.primary-menu_item.channel-horses.channel.channel-horses > span")));
element.click();
time.sleep( 15 )
###
driver.close()

我也试过

WebDriverWait(driver, 2222).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#ui-app-primary-menu > a.primary-menu_item.channel-poker.channel.channel-poker.ng-isolate-scope > span'))).click();

WebDriverWait(driver, 2222).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#ui-app-primary-menu > a.primary-menu_item.channel-horses.channel.channel-horses > span'))).click();

【问题讨论】:

  • 您知道WebDriverWait(driver, 20000) 意味着等待大约5.5 小时吗?
  • @Andersson 是的。它应该等到找到元素。我放了一个很大的值,好像我放了 1 秒它可能会失败。
  • 好的。但如果找不到元素,您的脚本将挂起 5.5 小时!
  • @Andersson 老实说,我还没有真正研究过异常处理。我想我会在找到另一种等待我猜的元素的方法后研究它。或者也许我不会因为睡眠等待工作而大惊小怪。
  • 这似乎是一个有角度的网站。你最好使用量角器。

标签: python selenium selenium-webdriver


【解决方案1】:

我想展示递归等待算法,我喜欢在类似的情况下使用它:

startTime = Date()
def recursive_wait(By: by):
        timeout = 3000
        duration = 0
        try:
            wait = WebDriverWait(driver, 5)
            wait.until(EC.visibility_of_element_located(by))
            wait.until(EC.element_t_be_clickable(by))
        except (TimeoutException, ElementNotVisibleException e):
            duration = startTime.compareTo(Date())
            if (timeout < duration):
                recursive_wait(by)

这等待元素 3000 秒,但检查元素每 5 秒出现一次。此外,您可以在 try 块中等待许多元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2014-05-07
    • 2020-02-23
    • 2022-11-28
    • 2015-03-17
    • 2023-03-15
    相关资源
    最近更新 更多