You need to enable JavaScript to run this app. 如何修改Python爬虫代码以仅打印10条爬取到的商品数据
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python爬虫代码以仅打印10条爬取到的商品数据

修改后可仅输出10条结果的代码

你只需要对遍历的序列做切片取前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')

# 取前10组匹配的商品名称和价格遍历输出
for t, p in list(zip(title, price))[:10]:
    print("{:<60} {:<30}".format(t.get_text(strip=True), p.get_text(strip=True)))

其他可选实现方式

如果你不想将zip对象转成列表,也可以通过计数器控制输出条数:

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')

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

内容的提问来源于stack exchange,提问作者armen kaymakmaian 4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 08:33:03