无法在NSE中刮取表格数据

2024-06-16 08:54:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从NSE网站上获取进展/下降-https://www1.nseindia.com/live_market/dynaContent/live_market.htm

预付款/预付款以表格格式显示在HTML中。但我无法检索网站上显示的实际数值

from bs4 import BeautifulSoup
import pandas as pd
import requests

url = "https://www1.nseindia.com/live_market/dynaContent/live_market.htm"
webpage = requests.get(url);
soup = BeautifulSoup(webpage.content, "html.parser");
for tr in soup.find_all('tr'):
  advance = tr.find_all('td')
  print(advance)

enter image description here

我只能得到一个空值或无值。我不确定我做错了什么。当我检查网站中的元素时,我看到了数值978904,但在Spyder中,这些元素中的值用连字符显示。有人能帮忙吗

enter image description here


Tags: httpsimportcomlive网站requestsmarkettr
1条回答
网友
1楼 · 发布于 2024-06-16 08:54:15

此页面使用JavaScript加载这些信息,但requests/BeautifulSoup无法运行JavaScript

使用DevToolsChrome/Firefox(tabNetwork,filterxhr)中,我发现JavaScript使用的url将其作为JSON数据加载,所以我甚至不必使用BeautifulSoup来获取它

import requests

url = 'https://www1.nseindia.com/live_market/dynaContent/live_analysis/changePercentage.json'
r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
data = r.json()
print(data['rows'][0]['advances'])
print(data['rows'][0]['declines'])
print(data['rows'][0]['unchanged'])
print(data['rows'][0]['total'])

顺便说一句:没有User-Agent它不会发送数据

相关问题 更多 >