【问题标题】:printing result of 2 for loops in same line在同一行中打印 2 个 for 循环的结果
【发布时间】:2018-06-07 11:29:36
【问题描述】:

我对 Python 中的网络抓取还很陌生;在阅读了有关该主题的大部分在线教程后,我决定试一试。我终于让一个站点正常工作,但输出格式不正确。

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)

输出

我希望将食物的名称与食物的相应价格并排打印,并用“-”连接...不胜感激,谢谢!

编辑:在下面的@Reblochon Masque cmets 之后 - 我遇到了另一个问题;正如您所看到的,有 0.00 美元是网站内置购物车的价值,我如何将其排除为异常值并继续向下移动,同时确保价格中的其他商品“向上移动”以对应吃正确的食物?

【问题讨论】:

    标签: python web-scraping printing-web-page


    【解决方案1】:

    最佳实践是在 for 循环中使用 zip 函数,但我们也可以这样做。这只是为了表明我们可以使用indexing 这两个列表。

    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】:

      你也许可以压缩这两个结果:

      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
      

      【讨论】:

      • 非常感谢!这正是我想要的!
      • 嘿,你知道如何删除异常值吗?我编辑了原始问题以反映您的代码
      • 你真的应该在这里问一个新问题;这是一个与第一个完全不同的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2022-10-06
      • 2014-11-25
      • 2021-08-31
      • 1970-01-01
      • 2018-10-17
      相关资源
      最近更新 更多