{ "cells": [ { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "132001000000.0\n" ] } ], "source": [ "from urllib.request import urlopen\n", "from urllib.parse import quote\n", "from bs4 import BeautifulSoup\n", "import time\n", "import re\n", "import json\n", "import pandas as pd\n", "\n", "select_year = 2021\n", "\n", "try:\n", " html = urlopen(\n", " f\"https://www.marketwatch.com/investing/stock/ibm/financials/balance-sheet\"\n", " )\n", " time.sleep(0.1)\n", " bsObj = BeautifulSoup(html.read(), 'html.parser')\n", "except Exception as e:\n", " print(e)\n", " print(\"Can't open url.\")\n", "else:\n", " bs_table = bsObj.find(name=\"table\", attrs={\"aria-label\":\"Financials - Assets data table\"})\n", " bs = bs_table.find(name=\"tr\", attrs={\"class\":\"table__row\"}).find_all(lambda tag: tag.name == 'th' and \n", " tag.get('class') == ['overflow__heading'])\n", " years_list = [i.div.contents[0] for i in bs][0:-1]\n", " years_list = map(int, years_list)\n", " bs = bs_table.find_all(name=\"tr\", attrs={\"class\":\"table__row is-highlighted\"})\n", " for i in bs:\n", " if i.td.div.contents[0] == 'Total Assets':\n", " string = i.find(\"div\", attrs={\"class\":\"chart--financials js-financial-chart\"}).attrs['data-chart-data']\n", " total_assets_list = string.split(',')\n", " total_assets_list = map(float, total_assets_list)\n", " total_assets = pd.DataFrame({\"year\":years_list,'total_asset':total_assets_list})\n", " print(total_assets.loc[total_assets['year']==2021,'total_asset'].to_list()[0])\n" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "