preface
Today, I went to work happily, because I made a lot of money from the stocks I bought, so I was happy! There must be no state at work that day. My mind is on the stock! A few random increases are a month's salary, which must be more fragrant. So today, I paid special attention to the stock price information. I watched it once in less than five minutes. Unexpectedly, I was caught by my boss and severely criticized! I'm really sorry, so I built a stock price CLI in Python. So I don't have to worry about the boss pulling my pigtail anymore!
- Read the code for the price you want.
- Wipe the latest price of the specified ticking machine.
- Displays the scraped price.
Let's start.
First, create a new python file. In this tutorial, I'll name my main.py. After you have a new python file, import sys, beautifulsoup and requests:
Main.py import sys import requests from bs4 import BeautifulSoup
After that, our cli will require the user to enter a tick as a command-line parameter. python3 main.py. Using the sys library, we can check whether the user has entered a tick, and if no code is provided or too much code is provided, make the CLI return an error. The CLI then defines the ticker variable as the second parameter provided by the user:
Main.py if len(sys.argv) > 2: print('You have specified too many tickers') sys.exit() if len(sys.argv) < 2: print('No ticker provided') sys.exit() ticker = sys.argv[1] # 0 = first argument and 1 = second argument
Now, our CLI will need to scrape the code provided because of its latest price. We can use the beautiful soup and requests library.
CLI will be from Yahoo Finance. It will need to change the URL it grabs according to the code entered by the user. Since the input tick is stored in the ticker variable, the CLI can change the URL code based variable according to the URL structure of Yahoo Finance, as shown below:
Main.py url = 'https://finance.yahoo.com/quote/' + ticker + '?p=' + ticker + '&.tsrc=fin-srch' response = requests.get(url)
For example, if the code provided is AMZN, the CLI will scratch the URL
If the code provided is AAPL, the CLI will scrape the URL
Full code:
import os import sys import requests from bs4 import BeautifulSoup if len(sys.argv) > 2: print('You have specified too many tickers') sys.exit() if len(sys.argv) < 2: print('No ticker provided') sys.exit() ticker = sys.argv[1] url = 'https://finance.yahoo.com/quote/' + ticker + '?p=' + ticker + '&.tsrc=fin-srch' response = requests.get(url)
Scrape stock price
For the actual capture part, first visit the stock price sample page on Yahoo Finance. I will choose AMZN for this tutorial. Locate the stock price element of the sample code and right-click it. This will cause a pop-up next to your cursor, click inspect alternative:
This will cause a large pop-up containing the DOM of this page to appear on the right side of the screen and highlight the selected stock price element in light blue:
Select and copy the class property of the highlighted element:
Now that you have the class attribute of this element, to scrape the latest stock price of this stock, please add the following code to main.py:
Main.py soup = BeautifulSoup(response.text, 'html.parser') price = soup.find('body').find(class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)') print('Latest stock price: ' + price.text.strip())
This code will find the stock price element through its class attribute and use price.text.strip()
Full code:
import os import sys import requests from bs4 import BeautifulSoup if len(sys.argv) > 2: print('You have specified too many tickers') sys.exit() if len(sys.argv) < 2: print('No ticker provided') sys.exit() ticker = sys.argv[1] url = 'https://finance.yahoo.com/quote/' + ticker + '?p=' + ticker + '&.tsrc=fin-srch' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') price = soup.find('body').find(class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)') print('Latest stock price: ' + price.text.strip())
One last thing!
Put the last piece of code into the try: statement and return an error. If the user enters an invalid tick key:
import os import sys import requests from bs4 import BeautifulSoup if len(sys.argv) > 2: print('You have specified too many tickers') sys.exit() if len(sys.argv) < 2: print('No ticker provided') sys.exit() ticker = sys.argv[1] url = 'https://finance.yahoo.com/quote/' + ticker + '?p=' + ticker + '&.tsrc=fin-srch' response = requests.get(url) try: soup = BeautifulSoup(response.text, 'html.parser') price = soup.find('body').find(class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)') print('Latest stock price: ' + price.text.strip()) except: print('Invalid ticker')
I have made the link to the full code one of my free gumload products. here. I often post cool projects and developer resources there, and I will be grateful to follow;)
It's time to test!
Now that you have the complete code, it's time to run some tests.
View Amazon's share price:
Look at Apple's share price:
Enter an invalid code:
epilogue
I hope this article can help you understand CLI development in Python and provide you with an interesting and useful Python project idea. The complete project code is required, which can be obtained here