Reading value from HTML page - nseindia

妖精的绣舞 提交于 2021-02-15 07:52:27

问题


I want to read "Open", "High" and "Close" value of NIFTY 50 from the below web page. https://www1.nseindia.com/live_market/dynaContent/live_watch/live_index_watch.htm

The below code was working before. Looks like there is some change in the webpage, I am not able to read the values as I am getting below error.

nifty_50_row = table.find_all('tr')[2]          # get first row of prices
AttributeError: 'NoneType' object has no attribute 'find_all'

Need your help to fix this issue.

My code is as below:

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

options = webdriver.ChromeOptions()
options.add_argument('headless') # disable Chrome browser GUI interface
driver = webdriver.Chrome(r'/usr/bin/chromedriver', options=options)
driver.get(url)
soup = bs4.BeautifulSoup(driver.page_source, 'html.parser')
table = soup.find('table', id='liveIndexWatch')

nifty_50_row = table.find_all('tr')[2]        

high_low = nifty_50_row.find_all('td')[3:7]   

h=high_low[1].text
c=high_low[3].text
l=high_low[2].text))
todays_open =high_low[0].text
todays_high = high_low[1].text
todays_low = high_low[2].text
prev_day_close = high_low[3].text

回答1:


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}

goal = ["open", "high", "previousClose"]


def main(url):
    r = requests.get(url, headers=headers).json()['data'][0]
    print(r)
    print("*" * 20)
    print([r[x] for x in goal])


main("https://www1.nseindia.com/live_market/dynaContent/live_watch/stock_watch/liveIndexWatchData.json")

Output:

{'timeVal': 'Apr 24, 2020 15:33:26', 'indexName': 'NIFTY 50', 'previousClose': '9,313.90', 'open': '9,163.90', 'high': '9,296.90', 'low': '9,141.30', 'last': '9,154.40', 'percChange': '-1.71', 'yearHigh': '12,430.50', 'yearLow': '7,511.10', 'indexOrder': '0.00'}
********************
['9,163.90', '9,296.90', '9,313.90']


来源:https://stackoverflow.com/questions/61422424/reading-value-from-html-page-nseindia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!