使用Python将数据填充到现有的Excel文件中

时间:2018-08-27 02:20:53

标签: python excel pandas

我正在尝试做的事情:

我正在使用Python将数据填充到现有的Excel文件中。

有效方法:

下面的代码成功将表导出到Excel文件“ Futures.xls”。

什么不起作用:

下面的代码从网站中提取表格并导出到Futures excel文件(100行)。随后的代码重新打开Futures文件并追加到Futures1 excel文件(200行)。但是,如果我多次继续运行后续代码,那么在运行代码时,我将无法获得超过200行,例如300行,依此类推。有人可以告诉我这个问题吗?

我的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import os

url = "https://quotes.ino.com/exchanges/contracts.html?r=NYMEX_NG"
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

Markets = []
Contracts =[]
Opens =[]
Highs =[]
Lows =[]
Lasts=[]
Changes=[]
Pcts=[]

data_rows = soup.findAll('tr')[3:]

for td in data_rows[:100]:
    Market = td.findAll ('td')[0].text
    Markets.append(Market)
    Contract = td.findAll('td')[1].text
    Contracts.append(Contract)
    Open = td.findAll('td')[2].text
    Opens.append(Open)
    High = td.findAll('td')[3].text
    Highs.append(High)
    Low = td.findAll('td')[4].text
    Lows.append(Low)
    Last = td.findAll('td')[5].text
    Lasts.append(Last)
    Change = td.findAll('td')[6].text
    Changes.append(Change)
    Pct = td.findAll('td')[7].text
    Pcts.append(Pct)
    Time = td.findAll('td')[8].text

    df = pd.DataFrame({'Contracts' :Contracts, 'Markets':Market,'Open':Opens, 'High':Highs, 'Low':Lows,'Last':Lasts,'Pct':Pcts})

    out_path = "C:\Sid\Futures.xls"
    writer = pd.ExcelWriter(out_path , engine='xlsxwriter')
    df.to_excel(writer,'Sheet2',index=False)
    writer.save()

    from openpyxl import load_workbook
    from openpyxl.utils.dataframe import dataframe_to_rows

    wb = load_workbook("C:\Sid\Futures.xlsx")
    ws = wb['Sheet2']

    from openpyxl import load_workbook
    from openpyxl.utils.dataframe import dataframe_to_rows

    wb = load_workbook("C:\Sid\Futures.xlsx")
    ws = wb['Sheet2']

    for row in dataframe_to_rows(df, header=None, index = True):
    ws.append(row)
    wb.save('C:\Sid\Futures1.xlsx')

其他:

此外,我需要什么代码,以便在我的网站更新时python自动运行?价格每15分钟更改一次。

0 个答案:

没有答案