【问题标题】:Selenium Python How to wait for options in a select to be populated?Selenium Python 如何等待选择中的选项被填充?
【发布时间】:2017-12-21 10:36:06
【问题描述】:

示例:等待

<select id="myselect"></select>

填充

<option value="123">One-two-three</option>

如何在 Python 中做到这一点?

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    您可以使用presence_of_element_locatedexplicit waiting 使用css 选择器定位元素:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "option[value='123']"))
        )
        print("Option loaded")
    except TimeoutException:
        print("Time exceeded!")
    
    #  Do Your Stuff
    

    【讨论】:

    • 非常感谢您的解决方案。在“finally”中,我打印出page_source,那个页面就是我想要的。但是,在页面打印出来之后,出现一条错误消息: raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:
    • @jhhPhi 嘿,对不起,我好像误用了finally 声明,现在应该这样做。我很高兴它有帮助,如果它有帮助并解决了您的问题,您应该 accept the answer,点击赞成票附近的绿色标记。
    • “超时”打印出来。这是否意味着在给定时间内,该语句永远不会返回 true?因为它没有返回true,所以它捕获了TimeoutException,然后代码继续。当代码循环 10 秒时,我的页面已经完全加载,所以我得到了我想要的页面。没有?
    • 只有在我删除“select#myselect >”后才有效。如果您在值周围添加了一对单引号,那么您的第一次尝试几乎是正确的。非常感谢您解决我的问题。
    • 对于特定的 Select,您可以像这样修改 EC.presence_of_element_located((By.CSS_SELECTOR, "#idOfYourSelect option[value=1]"))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多