Python Selenium中'Return outside function'错误的排查求助
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 thewhileloop andreturn) ends up outside the function. - Accidentally de-indenting the
elseblock so it sits at the same level as thewhileloop instead of thetrystatement (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:
- Added the missing import: You need to import
NoSuchElementExceptionfrom Selenium, otherwise Python will throw aNameErrorwhen that exception is triggered. - Strict indentation: All code inside
get_product_infouses 4-space indents (Python’s standard) under the function definition. Thereturnis safely inside thetryblock’s success path (you can also keep it in theelseblock—either works, but this flow is clearer). - 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. - 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

