Python 以 xlsx 格式输出文件

Python output file in xlsx format

我在 python 中编写了用于从网站抓取数据的代码。我无法以 .xlsx 格式保存数据。

这是我试过的代码:

from requests import Session
import pandas as pd
from bs4 import BeautifulSoup
import re 

def get_option_chain(symbol, expdate):

   if symbol == 'NIFTY':
      Base_url = ("https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbol="+symbol+"&date="+expdate)

      soup = BeautifulSoup(page.content, 'html.parser')
      ofTable = soup.find(id='octable')
      col_hdrs_name = [th_cell.text for th_cell in ofTable.select('thead th[title]')]
      col_hdrs_name = col_hdrs_name[1:-1]
      cols_num = len(col_hdrs_name)

      new_table = pd.DataFrame(columns=col_hdrs_name)

      rows_table = ofTable.select('tr')
      for row in rows_table:
          cols = row.select('td.ylwbg,td.grybg,td.nobg')
          colsval = [''.join(p.findall(c.text)) for c in cols]
          if len(cols) == cols_num:
              new_table = new_table.append(pd.Series(colsval, index=new_table.columns), ignore_index=True)

      print(new_table)
      # Here's the line of code I'm having trouble with
      new_table.to_csv('Option_Chain_Table_{}.csv'.format(symbol))



get_option_chain('NIFTY','19SEP2019')

尝试使用 to_excel 而不是 to_csv。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html