【问题标题】:Python - Selenium WebDriverWait does not work without breakpointPython - Selenium WebDriverWait 在没有断点的情况下无法工作
【发布时间】:2019-05-30 04:21:58
【问题描述】:

我正在尝试从

收集一些数据
https://www.91mobiles.com/phonefinder.php

我必须等待 ajax 调用才能获得“下一步”按钮,但 WebDriverWait 似乎被忽略(不会被命中)而没有断点。 以前它可以工作 2 周,但现在不行了。

  • 我以为是 web 驱动 -> 改成 chrome 而不是 firefox 但结果是一样的
  • 将每个包更新到最新 -> 相同
  • 尝试使用具有相同实现的 C# -> 有效,我不知道为什么 => 总结一下,也许问题不在他们的网站上

C# 语法:

Driver.ExecuteScript("window.scrollTo({ top: document.body.scrollHeight || document.documentElement.scrollHeight, behavior: 'smooth' });");

Wait.Until(s => s.FindElement(By.CssSelector('div#finder_pagination>div.listing-btns>div.listing-btns4>span')));

Driver.ExecuteScript("window.scrollTo({ top: 0, behavior: 'smooth' });");
// Work as expected
...

Python 语法:

# Scroll to bottom for AJAX loading
self.browser.execute_script('window.scrollTo({ top: document.body.scrollHeight || document.documentElement.scrollHeight, behavior: "smooth" });')

# timeout is 30 seconds, execution will be delayed until the 'NEXT' button found
self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div#finder_pagination>div.listing-btns>div.listing-btns4>span')))

# after that, scroll back to top
self.browser.execute_script('window.scrollTo({ top: 0, behavior: "smooth" });')
# The web does not wait, it scroll right away and execute the next code
...

提前致谢

【问题讨论】:

    标签: python-3.x selenium python-3.7 webdriverwait


    【解决方案1】:

    您的代码在我这边运行良好,但我认为这里可能会导致问题。 在您的wait.until() 中,您使用的是presence_of_element_located

    正如你所说,它以前工作过,现在不再工作了。我的猜测是该元素已找到但未完全加载,然后您调用滚动到顶部并没有使该元素出现。

    EC 的另一种方法是visibility_of_element_located。这将使用与存在相同的逻辑.. 但只有在允许使用

    可见时才会返回元素
    is_disaplayed()
    

    更改您的代码以改用此方法:

    driver.get('https://www.91mobiles.com/phonefinder.php')
    driver.execute_script('window.scrollTo({ top: document.body.scrollHeight || document.documentElement.scrollHeight, behavior: "smooth" });')
    wait = WebDriverWait(driver, 30)
    # timeout is 30 seconds, execution will be delayed until the 'NEXT' button found
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#finder_pagination .listing-btns4')))
    
    # after that, scroll back to top
    driver.execute_script('window.scrollTo({ top: 0, behavior: "smooth" });')
    

    您的 css_selector 工作正常,但正如您所见,我已将其更改为更简单、更易读的。

    【讨论】:

    • 不确定这是否是我正在寻找的内容,因为用你的代码替换我的代码并不能解决我的问题。 2 小时后用您的建议重写所有内容,它现在可以工作了。 Arghhh f*k 我的大脑,我什至不知道为什么。Upvoted 但是我的代表是
    • 令人困惑?!?!它是否有效?您能否提供有关此最终目标的更多详细信息?
    猜你喜欢
    • 2015-06-18
    • 2023-03-26
    • 2012-04-01
    • 1970-01-01
    • 2020-07-18
    • 2012-12-21
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多