[英]Continue for loop with while loop inside after exception?
我正在尝试使用 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”
我的目标是继续并完成循环,并忽略错误。
如何改进代码? 提前致谢
Induce WebDriverWait
() 和element_to_be_clickable
() 并使用 try..except 块如果找到元素然后单击 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.