我想在python中返回多个链接,但无法弄清楚如何。如果我打印link_href
I获取所有链接,但当我返回时,我只获得第一个链接并退出应用程序。有人可以帮我吗?
def main():
def get_links():
offset = 0
while int(offset) < 990:
url = f"https://krmeni.cz/kniha?offset={str(offset)}"
page_content = requests.get(url)
soup = BeautifulSoup(page_content.text, "html.parser")
file_path = "chatbot_data.csv"
offset += 10
for link in soup.find_all('a', {'class': 'white-btn'}):
title = link.string
link_href = link.get("href")
if link.string == "přidat odpověď":
continue
else:
return link_href
for link_href in get_links():
answer_url = f"https://krmeni.cz{get_links()}"
print(answer_url)
您的代码将在第一个if和else语句中退出。
if link.string == "přidat odpověď":
continue
else:
return link_href
在for循环之前初始化一个列表,并在else语句中追加link_href。完成执行for循环后,返回列表。就像这样。
link_list = []
for link in soup.find_all('a', {'class': 'white-btn'}):
title = link.string
link_href = link.get("href")
if link.string == "přidat odpověď":
continue
else:
link_list.append(link_href)
return link_list
或制作发电机,
for link in soup.find_all('a', {'class': 'white-btn'}):
title = link.string
link_href = link.get("href")
if link.string == "přidat odpověď":
continue
else:
yield link_href
找到第一个链接后,您的循环退出。使用列表理解:
return [link.get('href')
for link in soup.find_all('a', {'class': 'white-btn'})
if link.string == 'pridat odpoved']
这将返回包含所需链接的列表。
只使用生成函数yield而不是return
def main():
def get_links():
offset = 0
while int(offset) < 990:
url = f"https://krmeni.cz/kniha?offset={str(offset)}"
page_content = requests.get(url)
soup = BeautifulSoup(page_content.text, "html.parser")
file_path = "chatbot_data.csv"
offset += 10
for link in soup.find_all('a', {'class': 'white-btn'}):
title = link.string
link_href = link.get("href")
if link.string == "přidat odpověď":
continue
else:
yield link_href
for link_href in get_links():
answer_url = f"https://krmeni.cz{get_links()}"
print(answer_url)