You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup的find_all后,for循环仅输出单个结果求助

问题解决:BeautifulSoup爬取仅输出一个结果

你的问题出在print语句的位置——它被放在了for循环外面。循环过程中,每次迭代都会更新product_name、product_price这些变量的值,但循环结束后才会执行一次print,自然只会输出最后一个商品的信息。

修正后的代码:

from bs4 import BeautifulSoup
import requests

html_text = requests.get('https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-/pr?sid=6bo%2Cb5g&uniqBStoreParam1=val1&wid=11.productCard.PMU_V2').text
soup = BeautifulSoup(html_text, 'lxml')
items = soup.find_all('div', class_= '_13oc-S')

for start_scraping in items:
    product_name = start_scraping.find('div', class_ = '_4rR01T').text
    product_price = start_scraping.find('div', class_ = '_30jeq3 _1_WHN1').text
    # 处理可能没有评分的情况
    product_rating = start_scraping.find('div', class_ ='_3LWZlK')
    product_rating = product_rating.text if product_rating else '无评分'
    # 处理可能没有描述的情况
    product_description = start_scraping.find('li', class_ ='rgWa7D')
    product_description = product_description.text if product_description else '无描述'
    
    # 把print放到循环内,每遍历一个商品就打印
    print(f'Product Name: {product_name} \nProduct Price: {product_price} \nProduct Rating: {product_rating} \nProduct Description: {product_description}\n{"-"*50}')

关键修改点:

  • 将print语句缩进,纳入for循环的代码块中,确保每个商品信息都能被打印
  • 增加了字段存在性判断,避免部分商品缺少评分/描述时抛出AttributeError

内容的提问来源于stack exchange,提问作者hectorcchan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:06:23