为了账号安全,请及时绑定邮箱和手机立即绑定

用 Python 抓取表格数据

用 Python 抓取表格数据

宝慕林4294392 2021-11-09 20:02:09
我想使用网页抓取从网站获取数据,但在 to_html 中出现错误import requestsimport 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'
查看完整描述

3 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

请尝试以下操作:


pip install lxml

pip install html5lib

pip install BeautifulSoup4

现在您不需要导入请求。


import pandas as pd

import html5lib

table=pd.read_html('https://www.nseindia.com/live_market/dynaContent/live_watch/equities_stock_watch.htm') 

此外,如果您打算从国家证券交易所抓取股票数据,您可以使用 NSEpy,这是一个简单的 API 来获取印度公司的股票数据。


查看完整回答
反对 回复 2021-11-09
?
慕斯王

TA贡献1864条经验 获得超2个赞

您收到 AttributeError 因为 pd.read_html() 返回数据框列表,而列表没有属性“to_html”

来到解决方案,您提到的页面是使用javascript呈现的。BeautifulSoup无法从 javascript 呈现的页面中抓取数据。

要访问 Javascript 渲染的页面,您需要使用成熟的渲染引擎。您可以使用seleniumphantomJS来获取 javascript 数据。


查看完整回答
反对 回复 2021-11-09
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

尝试以下...


# !pip install webdriver-manager

import numpy as np

import requests

from bs4 import BeautifulSoup as bs

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

from webdriver_manager.chrome import ChromeDriverManager

DRIVER_PATH = '/path/to/chromedriver'

url= 'https://www1.nseindia.com/live_market/dynaContent/live_watch/equities_stock_watch.htm'

options = Options()

options.headless = False

driver = webdriver.Chrome(ChromeDriverManager().install())

driver.set_page_load_timeout(5)

try:

    driver.get(url)

except:

    pass

src= driver.page_source

driver.quit()

soup= bs(src, 'lxml')

table= soup.find_all('table')

table= pd.read_html(str(table[1]),header=0)[0].set_index('Symbol')

table


查看完整回答
反对 回复 2021-11-09
  • 3 回答
  • 0 关注
  • 204 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信