如何将函数输出作为另一函数输入 打通食谱爬虫自动流程
爬虫函数串联实现与代码优化方案
函数输出对接输入的实现步骤
原代码存在两个核心问题:trade_spider仅打印爬取结果、未对外输出可复用的链接列表;ingredient_spider硬编码了食谱链接,没有定义可接收参数的入口,按以下步骤改造即可实现自动串联:
1. 改造trade_spider为返回链接列表
把爬取到的链接存入列表并返回,同时处理相对路径问题(部分站点的链接会省略域名,直接调用会报错):
def trade_spider(): base_url = 'https://tasty.co' list_page_url = 'https://tasty.co/topic/best-vegetarian' source_code = requests.get(list_page_url) plain_text = source_code.text soup = BeautifulSoup(plain_text, 'lxml') recipe_links = [] for link in soup.find_all('a', {'class':'feed-item analyt-internal-link-subunit'}): href = link.get('href') # 拼接相对路径为完整可访问URL full_url = base_url + href if href.startswith('/') else href recipe_links.append(full_url) return recipe_links
2. 改造ingredient_spider支持传入URL参数
去掉硬编码的目标链接,新增URL作为函数入参:
def ingredient_spider(recipe_url): source_code = requests.get(recipe_url) new_text = source_code.text soup = BeautifulSoup(new_text, 'lxml') for ingredients in soup.find_all("li", {"class": "ingredient xs-mb1 xs-mt0"}): print(ingredients.text)
3. 串联两个函数自动运行
直接调用trade_spider拿到全量食谱链接,遍历后逐个传入ingredient_spider即可完成批量爬取:
if __name__ == "__main__": all_recipe_urls = trade_spider() for url in all_recipe_urls: ingredient_spider(url)
现有代码优化建议
- 增加异常捕获:给
requests.get逻辑加上try/except,处理超时、页面404、被反爬拦截等异常,避免单个链接出错导致整个爬虫中断。 - 添加模拟浏览器请求头:tasty这类站点会拦截无浏览器标识的爬虫请求,给
requests.get加上headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'},大幅降低请求被拦截的概率。 - 增加请求间隔:批量爬取时不要高频请求目标站点,每次调用请求前加
time.sleep(1)之类的延迟,避免触发站点反爬机制导致IP被封。 - 优化结果输出:不要仅把爬取的链接、食材打印到控制台,支持写入本地txt、csv文件,方便后续整理和复用数据。
- 增加去重逻辑:把已经爬取过的URL存入本地集合文件,下次运行时自动跳过已处理的链接,避免重复爬取浪费资源。
- 扩展函数返回值:让
ingredient_spider把提取到的食材列表返回而非仅打印,方便后续做食材分类、统计等二次处理。
内容的提问来源于stack exchange,提问作者Crying91312
相关产品推荐
相关产品推荐

