You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将Selenium循环爬取的字符串通过Pandas导出为CSV

循环爬取数据存入DataFrame并导出CSV的修正方案

问题根源

你当前的问题大概率是两个原因:

  • 每次循环时重新创建DataFrame,覆盖了之前的记录
  • 单条数据直接转DataFrame时用了错误的结构,导致数据方向颠倒

修正步骤

  1. 提前初始化数据收集容器:在循环开始前创建一个空列表,用来存储每一条爬取到的记录
  2. 循环内收集单条数据:把每次爬取的三个字段打包成字典,追加到列表中
  3. 统一生成DataFrame并导出:所有页面遍历完成后,再用列表生成DataFrame,最后导出CSV

修正后的代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd

# 初始化浏览器及登录操作(保留你的原有代码)
driver = webdriver.Chrome()
# ... 登录逻辑、获取所有Detail页面链接的代码 ...

# 初始化空列表,用于存储所有爬取数据
data_records = []

# 遍历Detail子页面(保留你的页面遍历、欧元筛选逻辑)
for page in detail_pages:
    # 进入子页面
    driver.get(page)
    
    # 筛选含欧元符号的页面逻辑(你的原有代码)
    if '€' not in driver.page_source:
        continue
    
    # 爬取目标字段(替换成你的实际元素定位方式)
    building_name = driver.find_element(By.XPATH, '//*[@id="building-name"]').text
    building_code = driver.find_element(By.XPATH, '//*[@id="building-code"]').text
    total_cost = driver.find_element(By.XPATH, '//*[@id="total-cost"]').text
    
    # 将单条数据转为字典,添加到列表
    single_record = {
        'building_name': building_name,
        'building_code': building_code,
        'total_cost': total_cost
    }
    data_records.append(single_record)

# 所有数据收集完成后生成DataFrame
result_df = pd.DataFrame(data_records)

# 导出CSV(index=False去掉索引列,utf-8-sig解决中文乱码)
result_df.to_csv('building_cost_data.csv', index=False, encoding='utf-8-sig')

# 关闭浏览器
driver.quit()

关键注意事项

  • 不要在循环内创建DataFrame:如果每次循环都执行pd.DataFrame(single_record),会不断覆盖之前的结果,最终只剩最后一条数据
  • 避免错误的DataFrame结构:直接用单个字典生成DataFrame时,默认会把字典的键作为列名,但如果用了orient='index'参数,就会把数据转成行方向,导致输出错误,所以统一用列表收集后再转是最稳妥的方式

内容的提问来源于stack exchange,提问作者Kapow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:22:37