2016-08-10 40 views
-1

我正在处理弹出问题,在点击按钮之前,这似乎是随机的。我想知道是否有任何方法可以检查元素是否显示并单击它,如果未显示,我希望它继续运行脚本。我当前的脚本不断收到错误。当显示弹出窗口时,我的脚本运行PERFECT。我的错误在如果找不到元素,Python的硒脚本将继续运行

onetouch = self.driver.find_element _by_xpath(""). 

这里发生在我的剧本是我的错误的图片:

enter image description here

 self.driver.get(redirecturl) 
     self.driver.implicitly_wait(180) 
     login_frame = self.driver.find_element_by_name('injectedUl') 
     # switch to frame to access inputs 
     self.driver.switch_to.frame(login_frame) 
     # we now have access to the inputs 
     email = self.driver.find_element_by_id('email') 
     password = self.driver.find_element_by_id('password') 
     button = self.driver.find_element_by_id('btnLogin') 



     # input your email and password below 
     email.send_keys('') 
     password.send_keys('') 
     button.click() 
     ############# 

     onetouch = self.driver.find_element_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a") 
     if onetouch.is_displayed(): 
      time.sleep(2) 
      onetouch.click() 
     else: 
      print "onetouch not present....continuing script" 
     button2 = self.driver.find_element_by_id('confirmButtonTop') 
     button2.click() 
     button3 = self.driver.find_element_by_name('dwfrm_payment_paypal') 
     # if you want to test the program without placing an order, delete the button3.click() below this......... 
     button3.click 

回答

0

其实find_element_by_xpath总是返回其中一个元素或抛出异常,所以,如果有没有提供的定位器元素,您无法执行is_displayed()。你应该尝试使用find_elements_by_xpath代替,并检查如下长度: -

onetouch = self.driver.find_elements_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a") 

    if len(onetouch) > 0: 
     time.sleep(2) 
     onetouch[0].click() 
    else: 
     print "onetouch not present....continuing script" 
     ------- 
+0

所以只需添加您的编辑给我的脚本? –

+0

@Tonyysanchez,是的,你应该编辑你的脚本与这个改变...... :) –

+0

生病让你知道它现在是怎么回事!谢谢 –

0

尝试以下操作:

from selenium.common.exceptions import NoSuchElementException 

try: 
    time.sleep(2) 
    self.driver.find_element_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a").click() 
except NoSuchElementException: 
    print "onetouch not present....continuing script" 
+0

刚刚尝试过。没有工作。 –

+0

你可以分享目标网页的HTML吗?显然,问题不在元素提供XPath' – Andersson

+0

即时通讯使用此自动签出后登录到我的贝宝,一个弹出式正式出来。 –