首页 > 解决方案 > python selenium 属性错误在while循环中使用.click()同时尝试除

问题描述

        i=1

        while i<=numberCountGlobal:
            time.sleep(1)
            print("i is: ",i)
            self.tempString='//*[@id="grid-view"]/div[{}]/div[4]/button'.format(i)
            try:
                self.driver.find_element_by_xpath(self.tempString).click()
                print("button press sucessfull")

            except NoSuchAttributeException:
                print("Nothing here.. skipping")

            i+=1

错误:

self.driver.find_element_by_xpath(self.tempString).click()
AttributeError: 'NoneType' object has no attribute 'click'

这会抛出一个属性错误,但是当我试图期待它时,它就是行不通的。当我关闭浏览器时,控制台中会出现代码错误。

它试图单击网站中的特定按钮,其中有很多或少数几个因此我使用了一个 while 循环来遍历“那里”的所有按钮

例如,如果..我删除.click()并保持原样,在我关闭浏览器之前它仍然没有错误,然后它就来了。我也不确定为什么当错误应该是一个属性错误时它会给出一个属性错误,NoSuchElementException因为当没有按钮时这个元素不存在!(是的,我也尝试过,但仍然存在同样的问题)以及except AttributeError

因此,如果一个按钮不存在,xpath 将不起作用,因为元素不存在,如果存在,它将位于正确的索引中,因此如果第 5 个按钮存在,它将是://*[@id="grid-view"]/div[5]/div[4]/button

标签: pythonseleniumwhile-loopselenium-chromedrivertry-except

解决方案


修复:在尝试之后添加隐式等待:

        i=1

        while i<=numberCountGlobal:
            time.sleep(1)
            print("i is: ",i)
            self.tempString='//*[@id="grid-view"]/div[{}]/div[4]/button'.format(i)
            try:
                self.driver.implicitly_wait(1)
                self.driver.find_element_by_xpath(self.tempString).click()
                print("button press sucessfull")

            except NoSuchAttributeException:
                print("Nothing here.. skipping")

            i+=1```

推荐阅读