Search code examples
pythonweb-scrapingbeautifulsoupurllib2stockquotes

Stock price data refresh


I am very new and I am getting totally stuck with recent task. I want to autorefresh stock price automatically as it is changing. I am scrapping nasdaq.com website for actual intraday price. I have a recent code:

import bs4 as bs
import urllib
tiker = input("zadaj ticker: ")
url = urllib.request.urlopen("http://www.nasdaq.com/symbol/"+tiker+"/real-time")
stranka = url.read()
soup = bs.BeautifulSoup(stranka, 'lxml')
print (tiker.upper())
for each in soup.find('div', attrs={'id': 'qwidget_lastsale'}):
    print(each.string)

I was only able to make an infinite loop while True but i get prints in lines despite i want to change only one line as actual price is changing. very thank you for your notes.


Solution

  • You can achieve it by printing "\b" to remove the previously printed string and then printing on the same line:

    import bs4 as bs
    import urllib
    import time
    import sys
    
    tiker = input("zadaj ticker: ")
    print (tiker.upper())
    written_string = ''
    while True:
        url = urllib.request.urlopen("http://www.nasdaq.com/symbol/"+tiker+"/real-time")
        stranka = url.read()
        soup = bs.BeautifulSoup(stranka, 'lxml')
        for each in soup.find('div', attrs={'id': 'qwidget_lastsale'}):
            for i in range(len(written_string)):
                sys.stderr.write("\b")
            sys.stderr.write(each.string)
            written_string = each.string
        time.sleep(1)