用 Python 抓取表格数据

我想使用网页抓取从网站获取数据,但在 to_html 中出现错误


import requests

import pandas as pd



 url= 

'https://www.nseindia.com/live_market/dynaContent/live_watch/equities_stock_watch.htm'

 html = requests.get(url).content

 df_list = pd.read_html(html)

 df = df_list.to_html(html)

 print (df)

 df.to_csv('my data.csv')

错误 :


AttributeError                            Traceback (most recent call last)

<ipython-input-35-61d14e08ca97> in <module>()

      5 html = requests.get(url).content

      6 df_list = pd.read_html(html)

----> 7 df = df_list.to_html(html)

      8 print (df)

      9 df.to_csv('my data.csv')


AttributeError: 'list' object has no attribute 'to_html'


宝慕林4294392
浏览 205回答 3
3回答

呼唤远方

请尝试以下操作:pip install lxmlpip install html5libpip install BeautifulSoup4现在您不需要导入请求。import pandas as pdimport html5libtable=pd.read_html('https://www.nseindia.com/live_market/dynaContent/live_watch/equities_stock_watch.htm')&nbsp;此外,如果您打算从国家证券交易所抓取股票数据,您可以使用 NSEpy,这是一个简单的 API 来获取印度公司的股票数据。

慕斯王

您收到 AttributeError 因为 pd.read_html() 返回数据框列表,而列表没有属性“to_html”来到解决方案,您提到的页面是使用javascript呈现的。BeautifulSoup无法从 javascript 呈现的页面中抓取数据。要访问 Javascript 渲染的页面,您需要使用成熟的渲染引擎。您可以使用selenium或phantomJS来获取 javascript 数据。

饮歌长啸

尝试以下...# !pip install webdriver-managerimport numpy as npimport requestsfrom bs4 import BeautifulSoup as bsfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsfrom webdriver_manager.chrome import ChromeDriverManagerDRIVER_PATH = '/path/to/chromedriver'url= 'https://www1.nseindia.com/live_market/dynaContent/live_watch/equities_stock_watch.htm'options = Options()options.headless = Falsedriver = webdriver.Chrome(ChromeDriverManager().install())driver.set_page_load_timeout(5)try:&nbsp; &nbsp; driver.get(url)except:&nbsp; &nbsp; passsrc= driver.page_sourcedriver.quit()soup= bs(src, 'lxml')table= soup.find_all('table')table= pd.read_html(str(table[1]),header=0)[0].set_index('Symbol')table
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python