【问题标题】:element not visible when click to link in the cycle在循环中单击链接时元素不可见
【发布时间】:2019-11-11 20:21:12
【问题描述】:

我从odds-co 类中获得了所有链接。然后在循环中,我click 在他们每个人身上。但有时我会收到错误element not visible。我知道这是由于时间问题。在我看来,指定time.sleep () 似乎不是一个非常正确的方法。我认为 可以使用webdriver wait,但我不明白如何。

rows = driver.find_elements_by_css_selector('.odds-co')
for i in rows:
    i.click()

网址 - https://www.oddsportal.com/soccer/england/efl-trophy/shrewsbury-macclesfield-WUgMbMnT/#over-under;2

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    expected_conditions.visibility_of()接收WebElement作为参数

    from selenium.webdriver.support import expected_conditions as ec
    from selenium.webdriver.common.by import By
    
    wait = WebDriverWait(driver, 10)
    rows = driver.find_elements_by_css_selector('.odds-co')
    for row in rows:
        wait.until(ec.visibility_of(row)).click()
    

    您也可以等待所有行都存在

    rows = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.table-container:not([style="display: none;"]) .odds-co')))
    for row in rows:
        row.click()
    

    【讨论】:

    • TimeoutException
    • @m0nte-cr1st0 但它适用于time.sleep()?添加了另一个选项。
    • 不,它也不适用于time.sleep()。我试过time.sleep(5)
    • @m0nte-cr1st0 我添加了另一个选项,但如果time.sleep() 不起作用,则不是时间问题(假设网站不是很慢)。
    • TypeError: 'str' object is not callable
    【解决方案2】:

    表中存在的行数为 15,但是当您在 DOM 中搜索时,它显示为 16.Over/Under 4.25 is missing.

    诱导WebDriverWaitpresence_of_all_elements_located()并检查12个元素并继续。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    driver=webdriver.Chrome()
    driver.get("https://www.oddsportal.com/soccer/england/efl-trophy/shrewsbury-macclesfield-WUgMbMnT/#over-under;2")
    rows=WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,".odds-co >a")))
    for row in range(len(rows)):
    
        rows = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".odds-co >a")))
        if row==11:
            continue
        else:
            rows[row].click()
    

    告诉我进展如何。

    【讨论】:

    • 这是因为网页上缺少该元素
    • 如何以编程方式识别这样的元素?
    • 是的,我们可以这样做。给我一些时间我会更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    相关资源
    最近更新 更多