xlsx格式的Python输出文件

时间:2019-09-15 18:41:55

标签: python excel pandas beautifulsoup xlsx

我已经用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')

1 个答案:

答案 0 :(得分:1)