我正在尝试获取社区类型的列表,并从网站上检索信息。但是,try语句存在问题。我需要包括try语句,因为列表中可能找不到社区类型。当我在不使用try语句的情况下运行代码时,代码将起作用。但是,如果包含不起作用,则始终返回异常。
import selenium ## web retrieval
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains ## needed
comm = ['Colorado Plateau Mixed Low Sagebrush Shrubland','Nowhere Land']
for names in comm:
driver = webdriver.Firefox()
driver.get("http://explorer.natureserve.org/servlet/NatureServe?init=Ecol")
SciName = driver.find_element_by_name('nameSpec')
SciName.send_keys(names)
checkbox = driver.find_element_by_name('noPunct')
checkbox.click() ### unselect box
SciName.submit() ## this submits it
try: SciName = driver.find_element_by_link_text(names) #
except selenium.common.exceptions.NoSuchElementException:
print names
print "Exception found"
driver.quit()
continue
SciName.click() ## enter this bad boy
print "I made it"
driver.quit() ### close the open window
print names
对为什么会发生这种情况有任何想法吗?我在另一个网页上使用了相同的代码,但效果很好。
打印错误e
返回:
Message: Unable to locate element: {"method":"link text","selector":"Colorado Plateau Mixed Low Sagebrush Shrubland"}`
和
Message: Unable to locate element: {"method":"link text","selector":"Nowhere Land"}
在尝试查找可以通过添加time.sleep进行验证的元素之前,该页面尚未加载:
SciName.submit() ## this submits it
time.sleep(2)
您将看到第一个成功,但是由于您没有得到符合您的搜索条件的记录,因此没有链接,因此有些链接仍然失败。
如果使用EC.presence_of_element_located
并打印错误,您将确切地看到发生了什么。
try:
element = WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.LINK_TEXT,names))
)
SciName = driver.find_element_by_link_text(names)
except (selenium.common.exceptions.NoSuchElementException,selenium.common.exceptions.TimeoutException) as e:
print(e)
您还需要导入以下内容:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
每次都没有try / except的情况下运行代码都会失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句