我有一个Selenium脚本,我在其中输入一系列网站,并获取一些数据。有时数据不存在,我只想在我的字符串上写一些类似“找不到x数据”的东西。当前脚本执行此操作:
#Getting "Status"
try:
strValue = strValue + ',' + browser.find_element_by_css_selector('#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(3) > span').text
except webdriver.NoSuchElementException:
StrValue = strValue + ',' + "Status not found"
当“状态”实际存在时,该脚本可以工作,但是id不会进入“except”部分。我的脚本顶部有这个:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Chrome(executable_path=r'C:\Selenium\chromedriver.exe')
browser.get('https://motorregister.skat.dk/dmr-front/dmr.portal?_nfpb=true&_nfpb=true&_pageLabel=vis_koeretoej_side&_nfls=false')
browser.implicitly_wait(10) # Will set the global wait to 10 seconds.gnash
我在这里尝试了解决方案:qazxsw poi但它没有用。
Python名称区分大小写,因此您可能需要:
Try except in python/selenium still throwing NoSuchElementException error
strValue = strValue + ',' + "Status not found"
不是NoSuchElementException
的一部分,它是webdriver
的一部分
selenium.common.exceptions
并确保在try:
strValue = strValue + ',' + browser.find_element_by_css_selector('#visKTTabset > div.h-tab-content > div.h-tab-content-inner > div:nth-child(12) > table > tbody > tr.stripes-even > td:nth-child(3) > span').text
except NoSuchElementException: # without webdriver.
StrValue = strValue + ',' + "Status not found"
区块之前宣布strValue
。
作为旁注,在Python中try except
应该是strValue