使用ThreadPool时遭遇maximum recursion depth exceeded错误的修复方法
修复
maximum recursion depth exceeded错误 错误原因
你的extract_all_social_link函数存在无限递归问题:函数内部直接调用自身,且没有任何终止条件,每次调用都会占用递归栈空间,直到超过Python默认的递归深度限制,触发报错。
def extract_all_social_link(bio_url): # 这里直接递归调用自己,无终止逻辑,必然导致栈溢出 data = extract_all_social_link(bio_url) return data
修复方案
你需要把函数内部的递归调用替换成实际的社交链接提取逻辑;如果确实需要递归,必须添加明确的终止条件。
方案1:替换为实际业务逻辑
假设你原本的意图是编写提取社交链接的代码,比如请求页面并解析内容,修改后的函数示例:
import requests from bs4 import BeautifulSoup def extract_all_social_link(bio_url): # 实际业务逻辑:请求页面、解析社交链接 try: response = requests.get(bio_url, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') # 解析页面中的社交平台链接(示例逻辑) social_links = [] for link in soup.find_all('a', href=True): href = link['href'] if any(platform in href for platform in ['twitter', 'facebook', 'instagram']): social_links.append(href) return social_links except Exception as e: print(f"提取链接失败: {e}") return []
方案2:若需递归则添加终止条件
如果业务确实需要递归(比如处理嵌套页面链接),必须添加终止条件,比如限制递归深度:
def extract_all_social_link(bio_url, depth=0, max_depth=5): # 终止条件:超过最大递归深度时停止 if depth >= max_depth: return [] try: response = requests.get(bio_url, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') social_links = [] # 提取当前页面的社交链接 for link in soup.find_all('a', href=True): href = link['href'] if any(platform in href for platform in ['twitter', 'facebook', 'instagram']): social_links.append(href) # 递归处理子链接(需判断是否符合递归条件) if href.startswith('http'): social_links.extend(extract_all_social_link(href, depth+1, max_depth)) return social_links except Exception as e: print(f"提取链接失败: {e}") return []
额外优化提示
你的run_extract_all_social_link函数中,user_data列表未被填充,记得在获取结果后添加数据:
try: data = future.result() # 将结果存入列表 user_data.append({"bio_url": bio_url, "social_links": data}) except Exception as exc: print(f"{bio_url} generated an exception: {exc}")
内容的提问来源于stack exchange,提问作者hoangv043
相关产品推荐
相关产品推荐

