检查某个元素,直到找到为止,然后单击该元素



嗨,我需要使用python Selenium检查元素。如果找到了元素,那么我需要点击它,或者点击下一页,再次搜索该元素。这种情况一直持续到找到元素为止。

我使用的代码是:

1. element_path="//span[contains(text(),'ABC Company')]" 
2. while True: 
3.  if(driver.find_elements_by_xpath(element_xpath)): 
driver.find_element_by_xpath(element_xpath).click() 
4.  else: driver.find_element_by_xpath("xpath to goto next page").click()

但是这个代码不起作用,因为我遇到了一个错误:没有这样的元素:{"方法":"xpath","选择器":"//span[包含(text((,'ABC公司(]"}

这个循环可以用其他方法完成吗?提前感谢

我不确定您是否也需要刷新页面,但我认为您应该检查len()函数,该函数将使用您提到的xpath具有find_elements

试试这个:

while True:
try:
if len(driver.find_elements(By.XPATH, "//span[contains(text(),'ABC Company')]")) > 0:
driver.find_element_by_xpath("//span[contains(text(),'ABC Company')]").click()
break
else:
driver.find_element_by_xpath("xpath to goto next page").click()
break
except:
pass

相关内容

最新更新