python - 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
解决方案
修复:在尝试之后添加隐式等待:
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```
推荐阅读
- excel - 等待一段时间而不暂停工作表
- python - 删除时间间隔在一小时内的相似记录
- javascript - 将元组的python列表发送到JavaScript数组不起作用
- javascript - 如何使用 jQuery 删除除特定类之外的所有 div 和其他 DOM HTML 元素
- mysql - 具有重叠范围的 GROUP BY CASE
- javascript - 用提琴手注入sql
- python - 是否可以在当前终端中运行 Python 选择?
- python - 如何从python中的列表列表中提取所有列和对角线?
- r - 条形图乱序
- c++ - 事件驱动编程和绿色线程:它们的关系是什么?