使用BeautifulSoup爬取亚马逊商品详情:span标签提取及格式问题
问题分析与解决方案
原代码失效原因
你写的get_pd函数之所以报错,是因为第一步pd = soup.find("div", attrs={'id':'detailBullets_feature_div'}).text.strip()已经把HTML元素转换成了字符串,而字符串没有find()方法(find()是BeautifulSoup元素对象的方法),因此触发AttributeError进入异常分支,返回空字符串。
修正后的代码(实现并列格式)
要把竖排的商品详情转换成可作为单列展示的并列格式,需要先提取每个详情项的文本,再用分隔符拼接成单行字符串:
# Function to extract Product Details def get_pd(soup): try: # 先找到详情容器的HTML元素(不是直接取文本) pd_div = soup.find("div", attrs={'id':'detailBullets_feature_div'}) # 提取容器内所有的列表项 detail_items = pd_div.find_all("li") # 遍历每个列表项,整理文本格式 formatted_details = [] for item in detail_items: # 提取单条详情的纯文本,自动去除多余换行和空格 clean_text = item.get_text(strip=True) # 统一标签与内容的分隔符格式(可选,让结果更整齐) clean_text = clean_text.replace(' : ', ': ') formatted_details.append(clean_text) # 用分号+空格拼接所有详情,变成单行字符串 pd = '; '.join(formatted_details) except AttributeError: pd = "No product details available" return pd
代码说明
- 先获取
detailBullets_feature_div的HTML元素对象,而不是直接取文本,这样才能继续用BeautifulSoup的方法提取子元素; - 用
find_all("li")拿到所有商品详情的列表项; - 遍历每个列表项,用
get_text(strip=True)提取干净的纯文本; - 最后用
join()方法把所有详情项拼接成单行,比如输出格式为:Brand: XXXX; Product Dimensions: XXXX; Item model number: XXXX,完美适配单列展示需求。
内容的提问来源于stack exchange,提问作者user27260026
相关产品推荐
相关产品推荐

