Python网页爬取报错'NoneType' object has no attribute 'find_all'求助
解决爬虫报错'NoneType' object has no attribute 'find_all'的问题
问题核心
你的代码报错是因为contenedor_de_productos = soup.find(class_="products-grid products-grid grid")返回了None,说明目标网页的结构已经变化,原选择器无法定位到产品容器元素。
修复方案
- 验证请求有效性
先检查req.status_code是否为200,确保请求成功获取网页内容。如果状态码异常,可能需要更新请求头或检查网络。 - 更新元素选择器
通过浏览器开发者工具(F12)查看当前网页结构,发现产品列表容器的类名已改为products-list products-list grid,替换原选择器即可。 - 增加非空判断
对find方法的返回值增加判断,避免后续调用find_all或.text时触发NoneType报错。
修改后的完整代码
import requests from bs4 import BeautifulSoup as bs headers = { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/71.0.3578.80 Chrome/71.0.3578.80 Safari/537.36", } url = "https://www.weplay.cl/new-arrival-funko-pop#/w/0/list/all/" req = requests.get(url) if req.status_code != 200: print(f"请求失败,状态码:{req.status_code}") else: soup = bs(req.text, 'html.parser') # 更新产品容器选择器 contenedor_de_productos = soup.find(class_="products-list products-list grid") if contenedor_de_productos: lista_de_productos = contenedor_de_productos.find_all('li', class_='product-item') for producto in lista_de_productos: texto_producto_elem = producto.find(class_='product-item-name') if texto_producto_elem: texto_producto = texto_producto_elem.text.replace('\n', '').replace('\t', '').replace(',', '').replace('"', '').strip() print(texto_producto) else: print("未找到产品容器元素,请检查网页结构或是否需要处理动态渲染")
额外建议
- 后续遇到网页结构变化时,优先用浏览器开发者工具核对元素的类名、标签等信息,及时更新选择器
- 养成对
find/find_all返回值做非空判断的习惯,提升代码稳定性
内容的提问来源于stack exchange,提问作者Marioloteitor
相关产品推荐
相关产品推荐

