当前位置: 代码迷 >> python >> 硒熊猫数据框构造函数未正确调用
  详细解决方案

硒熊猫数据框构造函数未正确调用

热度:101   发布时间:2023-06-27 21:18:46.0

此代码的目的是抓取网页并从表中提取数据,然后将其转换为pandas数据框。

抓取和数据提取进展顺利。

输出是这样的:

发布日期

时间

实际

预测

以前

2018年9月9日(八月)

21:30

0.7%

0.5%

0.3%

2018年8月8日(七月)

21:30

0.3%

0.2%

-0.1%

2018年7月9日(六月)

21:30

-0.1%

0.1%

-0.2%

2018年6月8日(五月)

21:30

-0.2%

-0.1%

-0.2%

2018年5月9日(四月)

21:30

-0.2%

-0.1%

-1.1%

2018年4月10日(3月)

21:30

-1.1%

-0.5%

1.2%

2018年3月8日(二月)

21:30

1.2%

0.8%

0.6%

2018年2月8日(1月)

21:30

0.6%

0.7%

0.3%

但是,当我尝试将其转换为数据帧时,出现了错误。

这是代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

url = 'https://www.investing.com/economic-calendar/chinese-cpi-743'

driver = webdriver.Chrome(r"D:\Projects\Tutorial\Driver\chromedriver.exe")
driver.get(url)
wait = WebDriverWait(driver,10)

while True:
    try:
        item = wait.until(EC.visibility_of_element_located((By.XPATH,'//*[contains(@id,"showMoreHistory")]/a')))
        driver.execute_script("arguments[0].click();", item)
    except Exception:break

for table in wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//*[contains(@id,"eventHistoryTable")]//tr'))):
    data = [item.text for item in table.find_elements_by_xpath(".//*[self::td or self::th]")]
    for data in data:
        df = pd.DataFrame(data.strip(), columns=['Release Date', 'Time', 'Actual', 'Forecast', 'Previous'])
        print(df)

这是错误:

追溯(最近一次通话):

文件“ D:/Projects/Tutorial/ff.py”,第22行,位于df = pd.DataFrame(data.strip(),columns = ['Release Date','Time','Actual','Forecast', '以前'])

文件“ C:\\ Users \\ Sayed \\ Anaconda3 \\ lib \\ site-packages \\ pandas \\ core \\ frame.py”在初始化行中引发ValueError('DataFrame构造函数未正确调用!')

ValueError:DataFrame构造函数未正确调用!

只需更改最后一部分

df = pd.DataFrame(columns=['Release Date', 'Time', 'Actual', 'Forecast', 'Previous'])
pos =  0
for table in wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//*[contains(@id,"eventHistoryTable")]//tr'))):
    data = [item.text for item in table.find_elements_by_xpath(".//*[self::td]")]
    if data:
        df.loc[pos] = data[0:5]
        pos+=1
print(df)
  相关解决方案