[英]Selenium/python 2.7 How to use if/else with find_element?
我想說的是,如果顯示element1,單擊,如果不檢查,如果顯示element2,單擊,等等。但是當元素不在那里時,我的代碼停止了。 如果element1在那,則單擊它,如果不在,則代碼停止,但我希望它繼續遍歷每個elif,直到找到一個為止,對您有所幫助。
from selenium import webdriver
fp = webdriver.FirefoxProfile('')
driver = webdriver.Firefox(firefox_profile=fp)
driver.set_window_size(1400, 1000)
driver.get('')
elem1 = driver.find_element_by_xpath("//img[@title='img1']")
elem = driver.find_element_by_xpath("//img[@title='img2']")
if elem.is_displayed():
elem.click()
print "true"
elif elem1.is_displayed():
elem1.click()
print "1true"
else:
print "false"
錯誤是
selenium,common.exceptions.NoSuchElementException:消息:無法找到元素:{“ method”:“ xpath”,“ selector”:“ // img [@ title ='img1']”}
該錯誤意味着根本找不到任何元素。 換句話說,它不顯示, 不存在 。
我將列出元素/定位符(假設您想縮放它),遍歷該列表並處理NoSuchElementException
錯誤。 單擊元素后退出循環:
from selenium.webdriver.common.by import By
locators = [
(By.XPATH, "//img[@title='img1']"),
(By.XPATH, "//img[@title='img2']")
]
for by, value in locators:
try:
driver.find_element(by, value).click()
break # exit once we click an element
except NoSuchElementException:
pass # element is not present - okay, move on
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.