Python Selenium脚本else语句未执行,需实现谷歌搜索结果异常处理
The problem with your current code is that Selenium's find_element_by_xpath() doesn't return a boolean when an element is missing—it throws a NoSuchElementException instead. That’s why your else block never runs; the script crashes before reaching that logic.
Here’s how to adjust your code to handle this properly using a try-except block:
First, make sure to import the required exception at the top of your script:
from selenium.common.exceptions import NoSuchElementException
Then update your conditional block:
elif inputOfUser == '': try: # Attempt to locate the result stats element result_stats = chrome.find_element_by_xpath('//*[@id="resultStats"]') # If found, update the table with the trimmed text table.update_cell(row, 5, result_stats.text[:-27]) except NoSuchElementException: # If the element doesn't exist, set the cell value to 0 table.update_cell(row, 5, "0")
Key Improvements:
- Wrapping the element lookup in a
tryblock lets us catch the exception when the element is missing, instead of letting the script crash. - If the element is found successfully, we proceed with updating the table as intended.
- When
NoSuchElementExceptionis raised, we execute theexceptblock and set the cell value to "0" as you wanted.
Pro Tip for More Robust Code:
To avoid false negatives caused by slow page loading, use WebDriverWait to wait for the element to appear before checking:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException, TimeoutException elif inputOfUser == '': try: # Wait up to 10 seconds for the element to load result_stats = WebDriverWait(chrome, 10).until( EC.presence_of_element_located((By.XPATH, '//*[@id="resultStats"]')) ) table.update_cell(row, 5, result_stats.text[:-27]) except (NoSuchElementException, TimeoutException): # Handle both missing element and timeout cases table.update_cell(row, 5, "0")
This accounts for scenarios where the element might exist but hasn’t finished loading yet, making your script more reliable.
内容的提问来源于stack exchange,提问作者KaanDev

