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

Python Selenium中'Return outside function'错误的排查求助

Return outside function error while using Selenium to scrape Amazon prices

I'm a programming beginner working on my first project: automating web scraping to get Amazon product prices continuously using Selenium. I keep getting a 'Return outside function' error. I know this is caused by indentation issues, but I've spent hours adjusting indents and still can't fix it.

Here's my code: the script runs in a while True loop with NoSuchElementException handling. It's supposed to print a message if elements aren't available, otherwise return product info:

def get_product_info(driver):
    title_id = "productTitle"
    price_id = "priceblock_ourprice"
    image_url_id = "landingImage"
    while True:
        try:
            product_title = driver.find_element_by_id(title_id).text
            product_price = driver.find_element_by_id(price_id).text[2:]
            product_image_url = driver.find_element_by_id(image_url_id).get_attribute('src')
        except NoSuchElementException:
            print('Not Available')
        except Exception as e:
            print (e)
        else:
            return { "title": product_title, "price": product_price, "img_url": product_image_url }

Please help me troubleshoot and fix this error.


Let's fix that 'Return outside function' error first, then tackle a couple of other potential issues in your code.

The Root Cause of the Indentation Error

That error pops up when Python can’t find a function wrapping your return statement. Looking at the code you shared, the indentation looks correct on paper—but it’s super easy to accidentally mess up indentation in Python, especially with nested blocks like while loops inside functions, and try/except/else inside loops.

Common missteps that cause this:

  • Forgetting to indent the lines right after def get_product_info(driver):—Python treats the function as empty, and all the code below (including the while loop and return) ends up outside the function.
  • Accidentally de-indenting the else block so it sits at the same level as the while loop instead of the try statement (though this might not trigger exactly this error, it breaks your code flow).
  • Mixing tabs and spaces for indentation—Python doesn’t tolerate this, and it can create invisible indentation mismatches.

Fixed Code with Proper Indentation & Improvements

Here’s the corrected version, plus tweaks to make it more robust:

from selenium.common.exceptions import NoSuchElementException  # Critical missing import!
import time

def get_product_info(driver):
    title_id = "productTitle"
    price_id = "priceblock_ourprice"
    image_url_id = "landingImage"
    
    while True:
        try:
            product_title = driver.find_element_by_id(title_id).text.strip()  # Clean up extra whitespace
            product_price = driver.find_element_by_id(price_id).text[2:]
            product_image_url = driver.find_element_by_id(image_url_id).get_attribute('src')
            
            # Return as soon as we successfully grab all elements
            return { 
                "title": product_title, 
                "price": product_price, 
                "img_url": product_image_url 
            }
            
        except NoSuchElementException:
            print('Product elements not available right now, retrying...')
            time.sleep(5)  # Wait 5 seconds before retrying to avoid getting blocked
        except Exception as e:
            print(f"Unexpected error: {str(e)}")
            time.sleep(10)  # Longer wait for unexpected issues

Key Fixes & Notes:

  1. Added the missing import: You need to import NoSuchElementException from Selenium, otherwise Python will throw a NameError when that exception is triggered.
  2. Strict indentation: All code inside get_product_info uses 4-space indents (Python’s standard) under the function definition. The return is safely inside the try block’s success path (you can also keep it in the else block—either works, but this flow is clearer).
  3. Added delays: Without time.sleep(), your infinite loop will hammer Amazon’s servers and get your IP blocked quickly. Short waits between retries are essential for responsible scraping.
  4. Trimmed whitespace: .strip() removes extra newlines or spaces that often clutter scraped product titles.

Double-Check for Invisible Issues

If the code you shared is exactly what you’re running, enable "show whitespace" in your code editor (most editors have this in the View menu). This will help you catch accidental tab-space mixes that cause hidden indentation errors.

内容的提问来源于stack exchange,提问作者Xavier Lim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:37:48