2017-07-08 66 views
-1

我只需要一点帮助,因为我已经开发了我的小脚本,但添加新功能会产生问题。问题是添加If If语句。脚本崩溃,如果它没有找到任何元素,所以我想通过放置一个ifelse条件来绕过它,即如果元素存在,它应该点击按钮,否则它应该移动到下一行。Python Selenium脚本在添加后会崩溃如果不然

下面是我的代码

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.") 

我是否只添加(如果)或者(如果driver.find_element_by_xpath( “”)的脚本崩溃在毫秒之内,甚至不会打开。

+1

这不是Python语法,所以它不应该是一个惊喜,它崩溃。 – jonrsharpe

+0

谢谢你让我知道,因为我在stackoverflow上搜索它,发现这些类似的语法无处不在,你能告诉我什么是Python的if else语法 –

+2

有许多Python的介绍和教程,请从一个那些:https://sopython.com/wiki/What_tutorial_should_I_read%3F。如果您只是要复制和粘贴代码段,请选择正确的语言! – jonrsharpe

回答

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.")