You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium脚本else语句未执行,需实现谷歌搜索结果异常处理

Fixing the Element Not Found Error to Return 0

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 try block 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 NoSuchElementException is raised, we execute the except block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:25:22