我只想打印给定数据的 10 个结果。我拥有的数据超过 10

I want to print only 10 results from the given data. the data i have is more than 10

import requests

from bs4 import BeautifulSoup

webpage = requests.get("https://www.spinneyslebanon.com/catalogsearch/result/?q=pepsi")

soup = BeautifulSoup(webpage.content, 'html.parser')

title = soup.find_all('a', 'product-item-link')
price = soup.find_all('span', class_='price')

for t, p in zip(title, price):

   print("{:<60} {:<30}".format(t.get_text(strip=True), p.get_text(strip=True)))

您应该可以使用 enumerate 作为计数器以在正确的数字处停止:

for index,tp in enumerate(zip(title, price)):
    if index >= 10:
        break
    t, p = tp
    print("{:<60} {:<30}".format(t.get_text(strip=True), p.get_text(strip=True)))

您可以 return 前 10 个价格和标题是这样的。

title = soup.find_all('a', 'product-item-link')[:10]
price = soup.find_all('span', class_='price')[:10]

"""
SAMPLE OUTPUT
Pepsi Pepsi Max - 330Ml                                      LBP 17,999
Pepsi Regular Bottle 330ml                                   LBP 3,999
Pepsi Black Regular Bottle 330ml                             LBP 3,999
Pepsi Diet Bottle 2.25L                                      LBP 10,999
Pepsi Regular 2.25L                                          LBP 10,999
Pepsi Regular Can 185ml                                      LBP 4,999
Pepsi Diet Bottle 1.25L                                      LBP 8,999
Pepsi Diet Can 185ml                                         LBP 4,999
Pepsi Regular Bottle 1.25L                                   LBP 8,999
Pepsi Diet Pet - 330Ml                                       LBP 3,999
""""

您可以使用这种方式获得前 10 个结果。只需在代码中的 for 循环之前添加这一行。

title, price = title[0:10], price[0:10]