代码之家  ›  专栏  ›  技术社区  ›  Little Phild

如何获取刷新DIV(Selenium)的数据

  •  2
  • Little Phild  · 技术社区  · 6 年前

    我现在的代码工作得很好,而且我一直在 StaleElementReferenceException

    下面是到目前为止我所拥有的

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.chrome.options import Options
    
    
    import time, sys
    
    option = webdriver.ChromeOptions()
    browser = webdriver.Chrome(executable_path='chromedriver', chrome_options=option)
    browser.get("example.com")
    
    sports_categories = browser.find_elements_by_css_selector('div.sidebar-wrapper')
    
    for sport in sports_categories:
       if sport.text == 'FOOTBALL':
            sport.click()
            time.sleep(2)
    
            sub_menus_html = browser.find_element_by_css_selector('div.category.lvl1.open  div.dropdown')
    
            print(sub_menus_html)
    

    2 回复  |  直到 6 年前
        1
  •  1
  •   PixelEinstein    6 年前

    click() ,因为在开始循环之前收集的元素列表

    下面是一个示例,说明如何循环并不断更新正在循环的元素的列表对象:

    option = webdriver.ChromeOptions()
    browser = webdriver.Chrome(executable_path='chromedriver', chrome_options=option)
    browser.get("example.com")
    
    sports_categories = browser.find_elements_by_css_selector('div.sidebar-wrapper')
    
    # add counter to keep track
    counter = 0
    for sport in sports_categories:
        #add category refresh here
        current_categories= browser.find_elements_by_css_selector('div.sidebar-wrapper')
        if current_categories[counter].text == 'FOOTBALL':    
            current_categories[counter].click()
            # I would recommend using something other than sleep to wait for load
            # like webdriverwait conditions combined with Expected Conditions
            time.sleep(2)
            sub_menus_html = browser.find_element_by_css_selector('div.category.lvl1.open  div.dropdown')
            print(sub_menus_html)
        counter += 1
    

    如果项目的长度 div.sidebar-wrapper

    刷新正在循环的元素列表

        2
  •  0
  •   Floyd    6 年前

    我不知道如何在python api中实现它,但是在nodejs webdriver api中,您可以 waitForVisible XPath

    //div[contains(@class, 'sidebar-wrapper')][text() = 'FOOTBALL']