Python爬虫生成DataFrame报错:指定3列但传入50列如何解决?
错误原因
你代码中的列表追加操作存在笔误:
- 你已经生成了存储单条商品三个字段、长度为3的
row列表,但实际执行的是rows.append(rows),也就是把整个rows列表自身作为元素追加到列表中,而非追加当前的单条数据row - 循环执行多次后,
rows的结构会变成多层嵌套的列表,完全不符合pandas要求的「每一项是长度为3的行数据」的结构,因此触发列数不匹配的报错
解决方法
把追加行的代码修改为rows.append(row)即可。修正后的完整代码如下:
import pandas as pd from bs4 import BeautifulSoup # 假设你之前已经完成了webdriver初始化、页面加载、results对象定义的相关逻辑 items = results.findAll("li") rows = [] page_source = wd.page_source soup = BeautifulSoup(page_source) for item in items: titleElement = item.find("h3", {"class": "s-item__title s-item__title--has-tags"}) priceElement = item.find("span", {"class": "s-item__price"}) dateElement = item.find("span", {"class": "POSITIVE"}) if titleElement and priceElement and dateElement: # strip()用于去掉字段前后的多余空格 row = [dateElement.text.strip(), titleElement.text.strip(), priceElement.text.strip()] rows.append(row) df = pd.DataFrame.from_records(rows, columns=["Purchase Date", "Title", "Price"]) # 如果后续要计算平均价格,可先把价格字段转为数值格式,参考代码如下: # df['Price'] = df['Price'].str.replace('¥','').str.replace(',','').astype(float) # print(df['Price'].mean()) df
内容的提问来源于stack exchange,提问作者littlebigship
相关产品推荐
相关产品推荐

