使用Python爬取网站内容打印品牌字段出现AttributeError该如何解决
错误原因
该AttributeError报错是因为部分productitem节点下不存在class为productitem--vendor的h3标签,BeautifulSoup的find()方法匹配不到对应元素时会返回None,直接调用None的text属性就会触发报错。另外代码中使用了Python内置关键字property作为循环变量名,属于不规范写法,可能引发隐性问题,建议更换。
修复方案
- 提取字段前先判断元素是否存在,匹配失败时设置默认值兜底
- 更换不符合规范的循环变量名
- 新增请求头模拟浏览器访问,避免站点反爬返回异常页面
修复后代码
import requests from bs4 import BeautifulSoup import pandas as pd import time # 增加请求头模拟浏览器,降低反爬拦截概率 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } url = 'https://dvago.pk/collections/cardio-vascular-system?page=1&grid_list=grid-view' r = requests.get(url, headers=headers) soup = BeautifulSoup(r.content, 'html.parser') content = soup.find_all('div', class_ = 'productitem') # 把循环变量从property改成product,避免和内置关键字冲突 for product in content: names= product.find('div', class_ = 'productitem--info') name= names.find('h2', class_ = 'productitem--title').text.strip() if names.find('h2', class_ = 'productitem--title') else '未知商品名' # 先判断品牌元素是否存在,不存在时赋值默认值 brand_tag = product.find('h3', class_ = 'productitem--vendor') brand = brand_tag.text.strip() if brand_tag else '未知品牌' print(name, brand)
内容的提问来源于stack exchange,提问作者user15290488
相关产品推荐
相关产品推荐

