Created
April 30, 2021 18:34
-
-
Save source-nerd/3a3bf0c27ee0967b78446a82944d5203 to your computer and use it in GitHub Desktop.
Scrape Market watch for real time stock price
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import requests | |
from bs4 import BeautifulSoup | |
class ScrapeMarketWatch: | |
def __init__(self, stock: str): | |
self.stock = stock.strip().lower() | |
self.url = 'https://www.marketwatch.com/investing/stock/' + self.stock + '?mod=over_search' | |
def get_page(self): | |
self.page = requests.get(self.url) | |
return self.page | |
# noinspection PyDictCreation | |
def get_price(self): | |
page = self.get_page() | |
soup = BeautifulSoup(page.content, 'html.parser') | |
result = {} | |
result['price'] = float("".join(soup.find("h3", {"class": "intraday__price"}).find(class_="value").text.split(","))) | |
result['change_point'] = float("".join(soup.find("span", {"class": "change--point--q"}).text.split(","))) | |
result['change_percentage'] = float(soup.find("span", {"class": "change--percent--q"}).text[:-1]) | |
result['total_vol'] = re.search(r"\d+[.]*\d*[a-zA-Z]*", soup.find("div", {"class": "range__header"}).find("span", {"class": "primary"}).text).group() | |
return result | |
#%% | |
if __name__ == "__main__": | |
tsla = ScrapeMarketWatch('TSLA') | |
print(tsla.get_price()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment