You need to enable JavaScript to run this app. Python Selenium Webdriver爬取URL数据出现重复内容如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium Webdriver爬取URL数据出现重复内容如何解决

问题根源

你代码中出现数据重复的核心原因是循环内从未更新用于解析的页面内容对象:

  • 你遍历用的t.tbody对应的BeautifulSoup实例t,明显是你在代码之外提前初始化的全局变量,整个循环过程中没有重新从新加载的driver页面中提取源码重新解析,所以每次循环处理的都是第一次请求返回的页面数据,自然出现大量重复。
  • 执行滚动加载的JS后没有预留渲染等待时间,也可能出现页面数据未加载完成就开始解析的问题。
  • 每次循环都新建、销毁Chrome driver实例属于不必要的操作,既降低效率也可能引发未知异常。

修正后的代码参考

import pandas as pd
import numpy as np
from selenium import webdriver
import chromedriver_binary
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
import time
from datetime import datetime

options = Options()
options.headless = True

lastDate = '2021-07-01'
firstDate = '2010-01-01'
time_object = time.strptime(lastDate, '%Y-%m-%d')
period2 = int(time.mktime(time_object))
period1 = int(period2 - 86400*200)
time_object = time.strptime(firstDate, '%Y-%m-%d')
period0 = time.mktime(time_object)
count = 1
# 全局只初始化一次driver即可
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(20)

while period2 >= period0:
    ed = datetime.fromtimestamp(period2)
    sd = datetime.fromtimestamp(period1)
    url=f"https://finance.yahoo.com/quote/%5EGSPC/history?period1={period1}&period2={period2}&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true"
    print(f"Working on {sd} {ed}, current count {count}")
    print(f"URL is {url}")

    driver.get(url)
    # 滚动后等待3秒让页面渲染完成
    js = "var q=document.documentElement.scrollTop=100000" 
    driver.execute_script(js)
    time.sleep(3)

    # 每次加载新页面后,都重新用当前页面源码生成BeautifulSoup对象
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    # 查找当前页面的tbody,不要用全局的旧对象
    tbody = soup.find('tbody')
    if not tbody:
        # 页面未加载到数据时跳过本次循环,避免报错
        period2 = int(period1)
        period1 = int(period2 - 86400*200)
        continue
   
    for row in tbody.findAll('tr'):
        cols = row.findAll('td')
        # 跳过非数据行(比如分红、拆股的提示行)
        if len(cols) < 7:
            continue
        date = cols[0].text
        date = datetime.strptime(date, "%b %d, %Y")
        date = date.strftime("%Y-%m-%d")
        open = cols[1].text.replace(',','')
        high = cols[2].text.replace(',','')
        low = cols[3].text.replace(',','')
        close = cols[4].text.replace(',','')
        adjclose = cols[5].text.replace(',','')
        volume = cols[6].text.replace(',','')
        hist = pd.DataFrame([[date,open,high,low,close,adjclose,volume]], columns=['Date', 'Open','High','Low','Close', 'Adj Close', 'Volume'])
        if count == 1:
            hist.to_csv('hist.csv', index=False, header=True)
        else:
            hist.to_csv('hist.csv', index=False, mode='a', header=False)  
        
        count += 1    

    period2 = int(period1)
    period1 = int(period2 - 86400*200)

# 所有循环结束后再关闭driver
driver.close()

额外优化点

  • 新增了非数据行的判断逻辑,避免遇到分红、拆股等特殊行时索引越界报错
  • 修正了原代码中Volumn的拼写错误为Volume
  • 复用driver实例后爬取速度会提升至少30%

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:51:01