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

Scraping Club练习3爬取问题:仅能获取首个商品如何修复?

问题解决方法

你的代码核心问题是定位容器错误:你用find_all抓取的是整个商品列表的外层容器(grid grid-cols-1 gap-4 sm:grid-cols-3类的div),这个容器在页面里只有1个,所以循环只会执行1次,且每次只能拿到容器里的第一个商品信息。

修正后的代码

from bs4 import BeautifulSoup
import requests
url = 'https://scrapingclub.com/exercise/list_basic/?page=1'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
# 改为定位每个商品的独立卡片容器
items = soup.find_all('div', class_='card')
count = 1
for i in items:
    item_name = i.find('h4').text.strip()
    item_price = i.find('h5').text.strip()
    print('%s ) Price: %s, Item Name: %s' % (count, item_price, item_name))
    count += 1

说明

当前页面中,每个商品都被包裹在class="card"的独立div里,通过find_all('div', class_='card')可以获取所有商品的卡片元素。循环遍历每个卡片时,find('h4')和find('h5')会精准定位当前卡片内的商品名称和价格,从而输出全部商品的序号、价格及名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:22:12