1

本网站操作:https ://www.livetulokset.com/

my_leagues = browser.find_element_by_id('my-leagues-list') # single element
leagues = my_leagues.find_elements_by_tag_name('li') # list of elements
for i in leagues:
    i.click()   # Click first league
    sleep(1)    # sleep second to be able to see the click in monitor
    browser.find_element_by_css_selector('a.menuTop__item:nth-child(1) > div:nth-child(2)').click() # click football icon

代码点击列表中的第一个联赛,然后点击足球图标返回主页。尝试单击列表中的第二个联赛时,由于页面刷新而发生 StaleElementReferenceException。如何防止这种情况发生?

编辑:

我真的需要在 for 循环期间不丢失 web 元素的解决方案。这个足球网站只是为了让你们在行动中测试我的问题。

4

2 回答 2

1

为什么不直接获取联赛的链接,然后再获取get它们。如果是当前链接,您可以跳过第一个链接links[1:]

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
url = 'https://www.livetulokset.com/'
driver = webdriver.Chrome()
driver.get(url)
links = [link.get_attribute('href') for link in WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#my-leagues-list a")))]
print(links)
for item in links:
    driver.get(link)
    # do something
于 2019-03-08T19:11:48.513 回答
0

浏览查看联赛列表中的每个联赛,您可以在辅助选项卡中打开每个联赛并切换到选项卡以执行必要的操作,最后关闭选项卡切换回主窗口,您可以使用以下解决方案:

  • 代码块:

    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
    import time
    
    options = webdriver.ChromeOptions()
    options.add_argument("start-maximized")
    options.add_argument("--disable-extensions")
    options.add_argument('disable-infobars') 
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://www.livetulokset.com/")
    handel_initially  = driver.current_window_handle
    my_hrefs = [my_leagues.get_attribute("href") for my_leagues in WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@id='my-leagues-list']/li//a")))]
    for href in my_hrefs:
        driver.execute_script("window.open('" + href +"');")
        WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
        handels_now =driver.window_handles
        driver.switch_to.window([x for x in handels_now if x != handel_initially][0])
        time.sleep(5) # perform your tasks within the new tab for each league
        driver.close()
        driver.switch_to_window(handel_initially)
    driver.quit()
    
于 2019-03-09T11:03:07.113 回答