Python Selenium - Try / Except不起作用

问题描述 投票:0回答:2

我有一个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 python-3.x selenium selenium-webdriver
2个回答
1
投票

Python名称区分大小写,因此您可能需要:

Try except in python/selenium still throwing NoSuchElementException error

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.