【问题标题】:selenium pandas dataframe constructor not properly calledselenium pandas 数据框构造函数未正确调用
【发布时间】:2019-02-27 19:15:30
【问题描述】:

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

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

输出是这样的:

发布日期

时间

实际

预测

上一个

2018 年 9 月 9 日(8 月)

21:30

0.7%

0.5%

0.3%

2018 年 8 月 8 日(7 月)

21:30

0.3%

0.2%

-0.1%

2018 年 7 月 9 日(6 月)

21:30

-0.1%

0.1%

-0.2%

2018 年 6 月 8 日(5 月)

21:30

-0.2%

-0.1%

-0.2%

2018 年 5 月 9 日(4 月)

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 日(一月)

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)

这是错误:

Traceback(最近一次调用最后一次):

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

init 中的文件“C:\Users\Sayed\Anaconda3\lib\site-packages\pandas\core\frame.py”,第 422 行 raise ValueError('DataFrame 构造函数未正确调用!')

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

【问题讨论】:

    标签: python pandas selenium


    【解决方案1】:

    只需对最后一部分进行更改

    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)
    

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      相关资源
      最近更新 更多