[英]How to exit a while True loop using a different format condition in Python?
[英]Exit while true loop to exit when there is none more to click using Python and Selenium
我正在使用 Python 和 Selenium 自动化步骤/单击网站。
我需要一个带有 'while true:' 循环的解决方案,当没有更多可点击时退出并转到下一行代码。
我一直在搜索并尝试了所有我能做的但无法让它工作。
我访问并需要自动化的网页具有每天变化的可变数量的页面。 在每个页面的底部都有一个“查看更多”按钮。 到目前为止,我所拥有的代码完成了向下滚动并单击每个按钮直到不再单击为止的工作。
问题是当没有更多可点击时,代码会因错误而退出。
如果有人可以帮助我解决问题,我将不胜感激。
当涉及到 Python(或任何编码)时,我是一个新手(但我正在尝试),所以请保持温和和描述性。
谢谢你。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
url = "https://web_page_i_want_to_open.html"
username = 'abcdefgh'
password = '123456'
browser = webdriver.Firefox()
browser.get(url)
time.sleep(5)
#find and click username field and insert login name
browser.find_element_by_xpath('/path_to_login_name_field').send_keys(username)
#find and click password field and insert password
browser.find_element_by_xpath('/path_to_password_field').send_keys(password)
#click login button
browser.find_element_by_xpath('"login-button"]').click()
#find and click "view more" button at bottom of page
while True:
browser.find_element_by_xpath('/button_at_bottom_of_the_page').click()
time.sleep(5)
#click "some_other_button_on_the_page"
#browser.find_element_by_xpath('/some_other_button_on_the_page').click()
捕捉 no such element 异常,当你得到它时,假设没有更多的页面。
while True:
try:
browser.find_element_by_xpath('/button_at_bottom_of_the_page').click()
time.sleep(5)
except NoSuchElementException:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.