如果找不到元素,Python selenium脚本将继续运行

时间:2016-08-10 01:36:35

标签: python selenium

我正在处理一个弹出问题,在我点击按钮之前这个问题似乎是随机的。我想知道是否有任何方法可以检查元素是否显示并单击它,如果没有显示,我希望它继续运行脚本。我当前的脚本一直出错。当弹出窗口显示时,我的脚本运行完美。我的错误发生在我的脚本

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

2 个答案:

答案 0 :(得分: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"
        -------

答案 1 :(得分:0)

请尝试以下操作:

http://localhost/myapp/