首页 > 解决方案 > 异常后在while循环中继续for循环?

问题描述

我正在尝试使用 Selenium 来抓取一堆网站,这些网站需要向下滚动并单击一个按钮。每个 url 具有相同的结构,但具有不同的点击次数。

我的代码:

for url in url_list:
while True:
    wd.get(url)
    last_height = wd.execute_script("return document.body.scrollHeight")
    while True:
        wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        #time.sleep = time for waiting
        time.sleep(3)
        new_height = wd.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height

    next_button = wd.find_element_by_link_text('next >>')
    next_button.click()

但是,代码只完成了第一个 url 并返回错误:“NoSuchElementException”。它没有继续循环,有时如果我更改了 url 列表,它会在循环中间停止并出现错误:“ElementClickInterceptedException”

我的目标是继续并完成循环,并忽略错误。

如何改进代码?提前致谢

标签: pythonselenium

解决方案


WebDriverWait归纳() 和() 并使用try..exceptelement_to_be_clickable块如果找到元素然后单击 else 中断。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

url_list = ['https://pantip.com/profile/2892172#topics','https://pantip.com/profile/5239396#topics','https://pantip.com/profile/349866#topics']
wd=driver=webdriver.Chrome()
for url in url_list:
    print(url)
    wd.get(url)
    while True:
        wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        try:
            next_button=WebDriverWait(wd,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'a.next.numbers')))
            next_button.click()
        except:
            print("No more pages")
            break

driver.quit()

推荐阅读