我只需要一些帮助,因为我已经开发了我的小脚本,但添加新功能会产生问题。问题是添加If else语句。如果脚本没有找到任何元素,脚本会崩溃所以我想通过放置一个ifelse条件来绕过它,即如果元素存在,它应该单击按钮,否则它应该移动到下一行。
以下是我的代码
driver.find_element_by_css_selector('input.whsOnd.zHQkBf').send_keys(password)
time.sleep(2)
driver.find_element_by_id("passwordNext").click()
time.sleep(2)
driver.get(comment_url)
time.sleep(2)
driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-default yt-uix-button-default yt-uix-button-empty yt-uix-button-has-icon no-icon-markup comment-action-buttons-renderer-thumb yt-uix-sessionlink sprite-comment-actions sprite-like i-a-v-sprite-like']").click()
time.sleep(2)
driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-small yt-uix-button-link comment-renderer-reply comment-simplebox-trigger']").click()
time.sleep(2)
driver.find_element_by_class_name("comment-simplebox-text").send_keys(comment)
time.sleep(2)
driver.find_element_by_xpath("//button[@class='yt-uix-button yt-uix-button-size-default yt-uix-button-primary yt-uix-button-empty comment-simplebox-submit yt-uix-sessionlink']").click()
time.sleep(2)
我要添加的代码是:
if driver.find_element_by_xpath ...... exists,
then
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
print("Zoom in 4x. Successful")
else
print("Element does not exist, it failed.")
我是仅添加(if)还是if(如果是driver.find_element_by_xpath(""),脚本在几毫秒内崩溃,甚至没有打开。
答案 0 :(得分:1)
您需要尝试捕获异常,如果捕获异常,请在except
块中执行某些操作。说到你的场景,你可能需要抓住selenium.common.exceptions.NoSuchElementException
。因此代码可能如下所示:
from selenium.common.exceptions import NoSuchElementException
try:
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
print("Zoom in 4x. Successful")
except NoSuchElementException:
print("Element does not exist, it failed.")