首页 > 解决方案 > 如何让一个函数的输出成为另一个函数的输入

问题描述

我正在为食谱网站制作网络爬虫,我想获取食谱的链接,然后使用该链接获取成分。我能够做到这一点,但只能通过手动输入链接来获取食谱。有没有办法获取链接然后使用此链接查看成分。此外,我将就如何使此代码更好地提出任何建议!

def trade_spider():
 url= 'https://tasty.co/topic/best-vegetarian'
 source_code = requests.get(url)
 plain_text = source_code.text
 soup = BeautifulSoup(plain_text, 'lxml')

 for link in soup.find_all('a', {'class':'feed-item analyt-internal-link-subunit'}):
           test = link.get('href')
           print(test)

def ingredient_spider():
 url1= 'https://tasty.co/recipe/peanut-butter-keto-cookies'
 source_code1= requests.get(url1)
 new_text= source_code1.text
 soup1= BeautifulSoup(new_text, 'lxml')
 for ingredients in soup1.find_all("li", {"class": "ingredient xs-mb1 xs-mt0"}):
      print(ingredients.text)

标签: pythonbeautifulsoupweb-crawler

解决方案


为此,请确保将您的输出设置为return而不是print(要了解差异,请尝试阅读此帖子的最佳答案:“打印”和“返回”之间的正式区别是什么?

然后,您可以将函数的输出用作变量,或将输出直接放入下一个函数。例如

x = tradespider()

或者

newFunction(tradespider())

推荐阅读