printing result of 2 for loops in same line

别等时光非礼了梦想. 提交于 2019-12-11 17:22:57

问题


I'm fairly new to web scraping in Python; and after reading most of the tutorials on the topic online I decided to give it a shot. I finally got one site working but the output is not formatted properly.

import requests
import bs4
from bs4 import BeautifulSoup
import pandas as pd
import time


page = requests.get("https://leeweebrothers.com/our-food/lunch-boxes/#")
soup = BeautifulSoup(page.text, "html.parser")

for div in soup.find_all('h2'): #prints the name of the food"
    print(div.text)
for a in soup.find_all('span', {'class' : 'amount'}): #prints price of the food
    print(a.text)

Output

I want both the name of the food to be printed side by side with the corresponding price of the food, concatenated by a "-" ... Would appreciate any help given, thanks!

Edit: After @Reblochon Masque comments below - I've run into another problem; As you can see there is a $0.00 which is a value from the inbuilt shopping cart on the website, how would i exclude this as an outlier and continue moving down the loop while ensuring that the other items in the price "move up" to correspond to the correct food?


回答1:


Best practice is to use zip function in the for loop, but we can do that this way also. This is to just to show we can do by using indexing the two lists.

names = soup.find_all('h2')
rest = soup.find_all('span', {'class' : 'amount'})
for index in range(len(names)):
    print('{} - {}'.format(names[index].text, rest[index].text))



回答2:


You could maybe zip the two results:

names = soup.find_all('h2')
rest = soup.find_all('span', {'class' : 'amount'})
for div, a in zip(names, rest):
    print('{} - {}'.format(div.text, a.text))
    # print(f"{div.text} - {a.text}")   # for python > 3.6


来源:https://stackoverflow.com/questions/50732023/printing-result-of-2-for-loops-in-same-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!