23
loading...
This website collects cookies to deliver better user experience
python3 main.py AMZN
in your terminal. In this tutorial, you will learn how to make a CLI with Python that:main.py
. Once you have your new python file, import sys
, BeautifulSoup
and requests
:import sys
import requests
from bs4 import BeautifulSoup
python3 main.py
. Using the sys
library, we can check if the user has entered a ticker and make the CLI return an error if no ticker was provided or if too many tickers were provided. This CLI will then define the ticker
variable as the second argument provided by the user: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
BeautifulSoup
and requests
libraries.ticker
variable, following yahoo finance's url structure, the CLI can change the url
variable based on the ticker like so:url = 'https://finance.yahoo.com/quote/' + ticker + '?p=' + ticker + '&.tsrc=fin-srch'
response = requests.get(url)
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)
inspect
option:class
property, to scrape this ticker's latest stock price, add the following code to 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())
price.text.strip()
.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())
try:
statement and return an error if the user entered an invalid ticker: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')