如何使用bs4将爬取的价格值存入CSV的单个单元格中?
问题描述
- 当前导出的CSV文件中,每个价格的字符被拆分成单个元素,分别放入不同单元格
- 需求:将完整的单个价格值放入CSV的一个单元格中
问题根源
代码中thewriter.writerow(price)这一行存在逻辑问题:writerow方法要求传入可迭代对象(如列表、元组),当直接传入字符串时,字符串会被视为字符的迭代器,每个字符会被当作独立列写入,最终导致价格被拆分到多个单元格。
修正后的代码
from bs4 import BeautifulSoup import requests from csv import writer url = 'https://whatmobile.web.pk/search/all?price-range=21721-50681&search=all&title=Mobile+Prices+%3E+RS.+100%2C000+and+Above' website = requests.get(url) soup = BeautifulSoup(website.content, 'html.parser') lists = soup.find_all('div', class_='product-grid8') with open('file.csv', 'w', encoding='utf-8', newline='') as file: thewriter = writer(file) header = ['price'] thewriter.writerow(header) for i in lists: price = i.find('div', class_='small').text newprice = price.replace(' PKR ', '') try: p = float(newprice) if p < 40000: # 将价格包装为列表,确保writerow将其识别为单个单元格内容 thewriter.writerow([price]) except ValueError: # 处理格式异常的价格数据,避免程序崩溃 print(f"无效价格格式: {price}")
关键修改说明
- 核心修正:将
thewriter.writerow(price)改为thewriter.writerow([price]),通过列表包装字符串,让writerow将整个价格作为单个单元格值写入 - 新增异常处理:捕获无法转换为浮点数的价格数据,避免程序中途终止
内容的提问来源于stack exchange,提问作者usmanhanif11
相关产品推荐
相关产品推荐

