gpt4 book ai didi

Python,Selenium,如何在元素消失后退出 while 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:35 24 4
gpt4 key购买 nike

我有一个文本不断变化的元素。

<small class="cell progress-name text-center ng-star-inserted">*some changing text*</small>

此元素中的文字消失后,该元素也随之消失。在元素消失后,我需要找到一种退出 while 循环的方法。

previous_value = None
while True:
current_value = browser.find_element_by_xpath('//*[@class="cell progress-name text-center ng-star-inserted"]')
if previous_value:
if current_value.text != previous_value:
print(current_value.text)
previous_value = current_value.text

else:
print(current_value)
previous_value = current_value.text

time.sleep(1)

现在我得到了 no such element: Unable to locate element 错误消息,我们将不胜感激。

最佳答案

您可以使用错误本身来了解元素是否已经消失。你只需要处理它并打破循环:

    previous_value = None
while True:
try:
current_value = browser.find_element_by_xpath('//*[@class="cell progress-name text-center ng-star-inserted"]')
except NoSuchElementException: # the element wasn't found
break # exit from the loop

if previous_value:
if current_value.text != previous_value:
print(current_value.text)
previous_value = current_value.text

else:
print(current_value)
previous_value = current_value.text

time.sleep(1)

记得导入异常 from selenium.common.exceptions import NoSuchElementException


还有另一种方法来处理这个问题。您可以使用 find_elements_by_xpath(在“elements”中带有“s”)。如果找不到任何内容,此函数将返回一个空列表,而不是抛出错误。

然后您可以检查列表是否为空,如果 True 则中断。

previous_value = None
while True:
current_value = browser.find_elements_by_xpath('//*[@class="cell progress-name text-center ng-star-inserted"]')
if not current_value:
break # the list is empty

if previous_value:
if current_value.text != previous_value:
print(current_value.text)
previous_value = current_value.text

else:
print(current_value)
previous_value = current_value.text

time.sleep(1)

我认为最好的选择是我给你的第一个,它更干净并且使用了 Glossary 中的 Python 原理。 :

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

关于Python,Selenium,如何在元素消失后退出 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58573610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com