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

Python爬虫读取CSV仅循环一次问题求助

Selenium爬虫读取CSV仅循环一次的解决方案

问题概述

开发基于Selenium的网页爬虫,目标从links.csv的指定列读取所有链接,抓取对应页面价格后写入新CSV文件。使用测试列表时程序正常运行,但读取CSV时仅循环一次就停止,无报错信息,写入CSV功能正常。

错误原因

直接遍历pandas读取的DataFrame对象时,迭代的是列名而非列中的链接数据。如果CSV只有一列链接,循环仅会执行一次(遍历列名),导致后续链接未被处理。此外原代码中df.append已被pandas弃用,且每次循环会覆盖结果DataFrame,导致数据重复或丢失。

修正后的代码

import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, WebDriverException

# 读取CSV中的链接列(假设链接列名为"Links",请根据实际列名修改)
df_links = pd.read_csv("links.csv")
# 提取链接列并过滤空值,转换为列表
links = df_links["Links"].dropna().tolist()

# 初始化存储结果的空DataFrame
result_df = pd.DataFrame(columns=["Product", "Price"])

browser = webdriver.Chrome()
try:
    for link in links:
        try:
            browser.get(link)
            # 抓取页面价格元素
            price_element = browser.find_element(By.CLASS_NAME, 'regular-price')
            price_text = price_element.text
            print(f"Price: {price_text}")
            # 将当前结果添加到结果DataFrame
            new_row = pd.DataFrame([[link, price_text]], columns=["Product", "Price"])
            result_df = pd.concat([result_df, new_row], ignore_index=True)
        except NoSuchElementException:
            print(f"无法找到价格元素: {link}")
            # 缺失价格时填充占位符
            new_row = pd.DataFrame([[link, "N/A"]], columns=["Product", "Price"])
            result_df = pd.concat([result_df, new_row], ignore_index=True)
        except WebDriverException as e:
            print(f"访问链接失败: {link}, 错误信息: {str(e)}")
            new_row = pd.DataFrame([[link, "访问失败"]], columns=["Product", "Price"])
            result_df = pd.concat([result_df, new_row], ignore_index=True)
finally:
    # 确保浏览器正常关闭
    browser.quit()

# 将结果写入CSV文件(不保留索引列)
result_df.to_csv("write.csv", index=False)
print("结果已写入write.csv")
print(result_df)

关键修正点

  • 正确遍历链接列:通过df["列名"]提取指定列的所有数据,转换为列表后遍历,确保每个链接都被处理。
  • 替换弃用方法:用pd.concat替代已弃用的DataFrame.append,避免版本兼容性问题。
  • 初始化空结果集:提前创建空DataFrame,避免循环中出现未定义变量的错误。
  • 添加异常处理:捕获页面元素缺失、链接访问失败等异常,保证程序不会因单个链接问题中断。
  • 规范导入方式:避免from pandas import *,改用import pandas as pd,减少命名冲突风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:40:58