使用 python 中的 selenium 我想點擊一個 html div 容器,如果它包含一些單詞并且找不到任何腳本必須退出。使用下面的代碼,如果有一個 div 包含text串列中的一個單詞,它就可以作業,但是我如何退出沒有找到單詞的地方?使用下面的代碼執行它,order.click因為它在 for 回圈之外。如果找到單詞,我只想執行order.click()并進一步處理腳本的其余部分break
text = ["Dog", "Cat", "Bird"]
for word in text:
try:
order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
if order != None:
print(f"found div with word: {word}")
break
except:
print(f"did NOT found div with word: {word}")
order.click()
# and more commands after this....
uj5u.com熱心網友回復:
import sys
而在除了:
text = ["Dog", "Cat", "Bird"]
is_found = False
for word in text:
try:
order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
if order != None:
print(f"found div with word: {word}")
is_found = True
break
except:
print(f"did NOT found div with word: {word}")
if is_found == False:
sys.exit()
order.click()
# and more commands after this....
這是如果您想退出整個腳本。
如果你只是不想運行order.click(),那么在你的try范圍內移動這一行:
try:
order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
if order != None:
print(f"found div with word: {word}")
order.click()
break
uj5u.com熱心網友回復:
我認為您需要在代碼的縮進部分中包含“order.click()”,以檢查是否在串列中找到了該專案,如下所示。
text = ["Dog", "Cat", "Bird"]
for word in text:
try:
order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
if order != None:
print(f"found div with word: {word}")
order.click()
break
except:
print(f"did NOT found div with word: {word}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/388854.html
標籤:Python 蟒蛇-3.x for循环 硒网络驱动程序
上一篇:函式級例外處理如何作業?
下一篇:IFS在回圈bash中讀取
