【问题标题】:selenium - wait for scrolldownselenium - 等待向下滚动
【发布时间】:2021-09-01 08:27:24
【问题描述】:

我正在尝试使用 selenium 自动从网页下载。

到目前为止,我的策略是实例化一个加载页面并单击下载按钮的 Firefox 驱动程序。但是,要可点击,按钮必须是可见的,即不被页面上的任何横幅覆盖(至少在我的理解中)。因此我需要向下滚动(我使用scrollIntoView())。如果我在向下滚动后立即运行button.click(),则下载不会开始,如果我在两者之间硬编码足够的超时时间,它就可以正常工作。有人可以帮我设置一个以向下滚动为条件的超时吗?

这是我的代码:

from selenium import webdriver

profilePath = '/path/to/my/firefox/profile'
profile = webdriver.FirefoxProfile(profilePath) 

driver = webdriver.Firefox(firefox_profile=profile)

driver.get("https://www.happyscribe.com/public/lex-fridman-podcast-artificial-intelligence-ai/164-andrew-huberman-sleep-dreams-creativity-the-limits-of-the-human-mind")

button = driver.find_element_by_id('btn-download')
target=driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)

time.sleep(10)

button.click()

这是按钮的html代码:

<button class="hs-btn-secondary small" id="btn-download" type="button">Download</button>

我将非常感谢任何有关如何从不同角度解决问题的直接帮助或建议。

【问题讨论】:

    标签: python html selenium selenium-webdriver web-scraping


    【解决方案1】:

    听起来您可能需要将WebDriverWait 诱导为可点击的元素。你可以这样做。它会等待元素同时为visible 和enabled,然后再点击。

    from selenium import webdriver
    import time
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    profilePath = '/path/to/my/firefox/profile'
    profile = webdriver.FirefoxProfile(profilePath) 
    
    driver = webdriver.Firefox(firefox_profile=profile)
    
    driver.get("https://www.happyscribe.com/public/lex-fridman-podcast-artificial-intelligence-ai/164-andrew-huberman-sleep-dreams-creativity-the-limits-of-the-human-mind")
    
    button = driver.find_element_by_id('btn-download')
    target=driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
    
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable(button))
    
    button.click()
    

    【讨论】:

    • 谢谢。您的实现会引发此错误:TypeError: selenium.webdriver.remote.webdriver.WebDriver.find_element() argument after * must be an iterable, not FirefoxWebElement 我将倒数第二行修改为以下内容:WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID,"btn-download"))) 不幸的是,这仍然无法解决问题。浏览器只是打开,向下滚动,但不执行点击。
    • 嗨,我正在使用 Chrome 浏览器,它运行良好,button = driver.find_element_by_id('btn-download') target=driver.execute_script("arguments[0].scrollIntoView({block: ' center'});", button) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID,'btn-download'))) button.click()
    • 太好了,谢谢,现在它对我有用!如果您将其作为答案重新发布,我可以接受。
    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2019-02-19
    • 2023-01-28
    相关资源
    最近更新 更多