python循环打印的结果在一行_在同一行中打印2个for循环的结果

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值