如何基于BeautifulSoup采集New Balance站点加载更多对应的全量鞋类商品
现有代码失效原因
- 纯
requests仅能获取服务端首次返回的静态HTML,“显示更多”触发的商品内容是前端JS通过异步请求接口加载的,不会包含在首次页面响应中,因此原代码仅能拿到首屏10款商品 - 目标页面是男装综合聚合频道,本身混杂服饰、配饰类商品,原代码没有设置类目校验逻辑,会将非鞋类内容一并爬取
全量动态商品获取实现
- 定位分页接口:打开浏览器开发者工具的网络面板,手动触发一次“显示更多”操作,筛选XHR类型请求,找到拉取后续商品列表的后端接口地址,这类接口一般携带页码、每页加载数量、当前频道ID等查询参数
- 构造循环拉取逻辑:从第1页开始逐页请求接口,请求时携带和浏览器一致的请求头(包含
User-Agent、Referer字段,避免被站点反爬策略拦截),当接口返回的商品列表为空、或返回商品总数与已爬取数量持平时,终止循环 - 数据解析直接针对接口返回的结构化内容,不依赖浏览器JS渲染后的DOM树,稳定性更高
鞋类内容筛选优化
在提取商品信息时增加校验规则,从结果中排除非鞋类内容:
- 优先从专属鞋类分类对应的DOM容器下提取商品,从根源减少无关内容混入
- 增加商品类目判定逻辑:如果商品节点带有服饰、配饰类目的标识(比如分类标签包含Apparel、Accessories类关键词),直接跳过不纳入结果集
- 校验商品对应的分类编码,仅保留鞋类枚举值对应的商品,排除其他类目的商品
优化后参考代码
import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Referer": "https://www.newbalance.com/men-2/" } all_products = [] current_page = 0 page_size = 10 # 循环拉取分页数据,直到没有更多商品 while True: # 替换为实际从网络面板抓到的分页接口地址,适配站点参数规则 page_url = f"https://www.newbalance.com/on/demandware.store/Sites-newbalance_us-Site/default/Search-UpdateGrid?cgid=men-shoes&start={current_page*page_size}&sz={page_size}" resp = requests.get(page_url, headers=headers) soup = BeautifulSoup(resp.text, "html.parser") product_nodes = soup.find_all('div', class_='product product-tile') # 单页无商品时终止循环 if not product_nodes: break for res in product_nodes: # 非鞋类内容过滤:命中服饰、配饰类目标签的直接跳过 category_tag = res.find('div', class_='product-category') if category_tag and any(keyword in category_tag.text for keyword in ["Apparel", "Accessories"]): continue # 提取鞋类商品核心字段 product_info = { "name": res.find_all('a')[1].text.strip(), "price": res.find('div',class_='product-pricing').text.split()[0], "image": res.find("img")['data-original'], "detail_url": res.find('a',class_='product-image')['href'] } all_products.append(product_info) current_page += 1 # 输出最终全量鞋类商品结果 for product in all_products: print("____________________") print(product) print("*******************************")
实际使用时需要根据站点最新的页面结构调整接口地址、校验关键词,适配站点迭代后的节点规则,避免解析失效。
内容的提问来源于stack exchange,提问作者StackNoob
相关产品推荐
相关产品推荐

