├── .gitignore ├── LICENSE ├── README.md ├── bse.py └── moneycontrol.py /.gitignore: -------------------------------------------------------------------------------- 1 | todo.txt 2 | __pycache__/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Python-News-Scraper 3 | A program that scrapes for announcements from [moneycontrol.com](www.moneycontrol.com) so that traders can take informed decision. 4 | Here is how to get started, 5 | 6 | 7 | import moneycontrol as mc 8 | 9 | # First parameter is the ticker symbol 10 | stock = mc.MoneyControl("ONGC") 11 | 12 | The "stock" object has 3 main methods at present that can be used to extract announcements from Money Control. 13 | 14 | ### fetch_a(page_no=1) 15 | This method is used to fetch announcements from the given page number. By default, page_no is 1. It returns a list of dictionary with all the values in it. 16 | 17 | # Fetching the announcements on page number 3 ofthe website 18 | stock.fetch_a(3) 19 | 20 | # Here is the output after running this method. 21 | [ 22 | { 23 | 'content':'Oil & Natural Gas Corporation Limited has informed the Exchange regarding Change in Director(s) of the company.', 24 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=10266461', 25 | 'date':'4th-Jan-2018 14:11', 26 | 'title':' Oil & Natural Gas Corporation Limited ', 27 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oil-natural-gas-corporation-limited-10266461.html' 28 | }, 29 | { 30 | 'content':'Pursuant to Regulation 30 of Securities and Exchange Board of India (Listing Obligations and Disclosure Requirements) Regulations, 2015, we hereby inform that Shri T K Sengupta, Director (Offshore), has ceased to be Director of the Company upon his attaining superannuation on 31.12.2017.', 31 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=10266101', 32 | 'date':'4th-Jan-2018 13:21', 33 | 'title':'Oil and Natural Gas Corporation - Change in Directorate ', 34 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oilnatural-gas-corporation-changedirectorate-10266101.html' 35 | }, 36 | { 37 | 'content':'The Exchange had sought clarification from the Company with respect to news item captioned "Venezuela\'\'s PDVSA misses debt payments, used Russian bank to pay ONGC". The response from the Company is enclosed.', 38 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9926541', 39 | 'date':'15th-Nov-2017 16:56', 40 | 'title':' Oil & Natural Gas Corporation Limited ', 41 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oil-natural-gas-corporation-limited-9926541.html' 42 | }, 43 | { 44 | 'content':'Reply to Clarification on media report.', 45 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9925541', 46 | 'date':'15th-Nov-2017 16:24', 47 | 'title':'Oil and Natural Gas Corporation - Updates ', 48 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oilnatural-gas-corporation-updates-9925541.html' 49 | }, 50 | { 51 | 'content':'The Exchange has sought clarification from Oil & Natural Gas Corporation Ltd with respect to news article appearing on moneycontrol.com on November 13, 2017 titled "Venezuela likely to go bankrupt in a day?."The reply is awaited.', 52 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9860941', 53 | 'date':'13th-Nov-2017 14:23', 54 | 'title':'Oil and Natural Gas Corporation - Clarification sought from Oil & Natural Gas Corporation Ltd ', 55 | 'pdf_link':None 56 | }, 57 | { 58 | 'content':'Oil & Natural Gas Corporation Limited has informed the Exchange regarding Change in Director(s) of the company.', 59 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9719361', 60 | 'date':'2nd-Nov-2017 12:20', 61 | 'title':' Oil & Natural Gas Corporation Limited ', 62 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oil-natural-gas-corporation-limited-9719361.html' 63 | }, 64 | { 65 | 'content':'Shri A K Srinivasan, Director Finance, has ceased to be Director of the Company upon his attaining superannuation on 31.10.2017', 66 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9717921', 67 | 'date':'2nd-Nov-2017 11:15', 68 | 'title':'Oil and Natural Gas Corporation - Change in Directorate ', 69 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oilnatural-gas-corporation-changedirectorate-9717921.html' 70 | }, 71 | { 72 | 'content':"Un-audited Financial Results for the second Quarter and Half Year ended 30th September, 2017- Auditors''Limited Review Report", 73 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9660001', 74 | 'date':'28th-Oct-2017 16:58', 75 | 'title':'Oil and Natural Gas Corporation - Updates ', 76 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oilnatural-gas-corporation-updates-9660001.html' 77 | }, 78 | { 79 | 'content':"ONGC declares results for Q2 FY''18; records impressive production performance", 80 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9659761', 81 | 'date':'28th-Oct-2017 16:37', 82 | 'title':'Oil and Natural Gas Corporation - Press Release / Media Release ', 83 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oilnatural-gas-corporation-press-release-media-release-9659761.html' 84 | }, 85 | { 86 | 'content':'Pursuant to Regulation 30 of Securities and Exchange Board of India (Listing Obligations and Disclosure Requirements) Regulations, 2015, it is hereby inform that Govt. of India has nominated Dr. Sambit Patra, as an Independent Director on the Board of the Company.The Board of Directors of the Company have also approved induction of Dr. Sambit Patra, as an Additional Director with effect from 28th October, 2017.', 87 | 'link':'http://www.moneycontrol.com/stocks/stock_market/corp_notices.php?autono=9658841', 88 | 'date':'28th-Oct-2017 15:56', 89 | 'title':'Oil and Natural Gas Corporation - Change in Directorate ', 90 | 'pdf_link':'http://www.moneycontrol.com/stocks/reports/oilnatural-gas-corporation-changedirectorate-9658841.html' 91 | } 92 | ] 93 | 94 | Each announcement is described using 5 keys, namely: 95 | 96 | - **content** - The small description of the announcement present on the website. 97 | - **link** - The exact link of the announcement page from where the data is scraped. 98 | - **date** - The date and time of the announcement 99 | - **title** - The title of the announcement 100 | - **pdf_link** - The PDF link of the announcement if present, otherwise, None 101 | 102 | -------------------------------------------------------------------------------- /bse.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import bs4 3 | import pytz 4 | 5 | # For this to work I need to convert the ticker symbol to security code 6 | SEARCH_URL = "http://www.bseindia.com/corporates/ann.aspx?curpg=1&annflag=1&dt=&dur=D&dtto=&cat=&scrip=%s&anntype=C" 7 | PREFIX_URL = "http://www.bseindia.com" 8 | 9 | 10 | class BSE(object): 11 | 12 | def __init__(self, security_code): 13 | 14 | # Declaring all the instance variable for the class 15 | self.security_code = security_code 16 | self.a = [] # Stores the announcements listed on the given page 17 | self.more_anno_link = "" # Link of the announcement page for the company 18 | self.more_news_link = "" # Link of news page for the company 19 | self.template_next_a_page = "" # For storing the link of the next page of the announcement 20 | self.a_page_links = [] # Stores the list of links all the announcement pages. 21 | self.link = "" # Link to the front page of the company we are looking for on moneycontrol 22 | self.present_a_page = 0 23 | 24 | self.fetch_ticker() 25 | # self.__fetch_a_next_page_link() 26 | 27 | 28 | def fetch_ticker(self): 29 | try: 30 | self.link = SEARCH_URL % self.security_code 31 | r = requests.get(self.link) 32 | if r.status_code==200: 33 | print("Fetched page for ticker : "+self.security_code) 34 | # Creating a bs4 object to store the contents of the requested page 35 | self.soup = bs4.BeautifulSoup(r.content, 'html.parser') 36 | print("Fetched page successfully") 37 | 38 | elif r.status_code==404: 39 | print("Page not found") 40 | else: 41 | print("A different status code received : "+str(r.status_code)) 42 | 43 | except requests.ConnectionError as ce: 44 | print("There is a network problem (DNS Failure, refused connectionn etc.). Error : "+str(ce)) 45 | raise Exception 46 | 47 | except requests.Timeout as te: 48 | print("Request timed out. Error : "+str(te)) 49 | raise Exception 50 | 51 | except requests.TooManyRedirects as tmre: 52 | print("The request exceeded the maximum no. of redirections. Error : "+str(tmre)) 53 | raise Exception 54 | 55 | except requests. requests.exceptions.RequestException as oe: 56 | print("Any type of request related error : "+str(oe)) 57 | raise Exception 58 | 59 | 60 | def __fetch_a_next_page_link(self): 61 | 62 | # Fetches the template URL for fetching different announcement pages 63 | r = requests.get(self.more_anno_link) 64 | announcement_soup = bs4.BeautifulSoup(r.content, 'html.parser') 65 | # Checking whether the link for the next page is available or not 66 | if len(announcement_soup.find("div", attrs={"class":"gray2_11"}).find_all("a")) > 0: 67 | a = announcement_soup.find("div", attrs={"class":"gray2_11"}).find_all("a")[0]["href"] 68 | self.template_next_a_page = PREFIX_URL + a[0:-1] # Removing the page no. of the given link so that it becomes general link 69 | 70 | 71 | def fetch_a(self, page_no=1): 72 | 73 | if self.has_a(self.template_next_a_page + str(page_no)): 74 | 75 | # Clear all the previous data in "a" instance variable 76 | self.a = [] 77 | 78 | r = requests.get(self.template_next_a_page + str(page_no)) 79 | 80 | self.present_a_page = page_no 81 | 82 | announcement_soup = bs4.BeautifulSoup(r.content, 'html.parser') 83 | raw_links = announcement_soup.find_all("a", attrs={"class":"bl_15"}) 84 | 85 | # List of links of all the announcements on the given page 86 | list_of_links = [] 87 | for x in raw_links: 88 | link = PREFIX_URL + x['href'] 89 | list_of_links.append(link) 90 | a = requests.get(PREFIX_URL + x['href']) 91 | anno_page = bs4.BeautifulSoup(a.content, "html.parser") 92 | 93 | pdf_link = "" 94 | title = "" 95 | content = "" 96 | 97 | date = next(anno_page.find("p", attrs={"class":"gL_10"}).children) 98 | date = self.format_date(date) 99 | 100 | 101 | # Checking whether the title of the announcement is available or not 102 | if anno_page.find("span", attrs={"class":"bl_15"}): 103 | title = anno_page.find("span", attrs={"class":"bl_15"}).text 104 | 105 | # Checking whether content is available or not 106 | if anno_page.find("p", attrs={"class":"PT10 b_12"}): 107 | content = anno_page.find("p", attrs={"class":"PT10 b_12"}).text 108 | 109 | # Checking whether the PDF link is availableor not 110 | if anno_page.find("p", attrs={"class":"PT5"}).find("a"): 111 | pdf_link = PREFIX_URL + anno_page.find("p", attrs={"class":"PT5"}).find("a")["href"] 112 | 113 | 114 | anno = {"link":link, "pdf_link":pdf_link, "content":content, "title":title, "date":date} 115 | self.a.append(anno) 116 | 117 | else: 118 | self.a = [] 119 | 120 | return self.a 121 | 122 | 123 | def has_a(self, link): 124 | result = False 125 | r = requests.get(link) 126 | soup = bs4.BeautifulSoup(r.content, "html.parser") 127 | a = soup.find_all("p", attrs={"class":"gL_10"}) # Finding the list of the all the dates available on the page 128 | if len(a)>0: 129 | result = True 130 | 131 | return result 132 | 133 | 134 | def fetch_all_a_pages(self): 135 | i = 2 136 | # fetch the announcement on first page only when this instance variable is empty 137 | if self.template_next_a_page == "": 138 | self.fetch_a() 139 | link = self.template_next_a_page+str(i) 140 | while self.has_a(link): 141 | link = self.template_next_a_page+str(i) 142 | print("Page added : "+str(i)) 143 | self.a_page_links.append(link) 144 | i += 1 # Keep incrementing the value of i to check the next page 145 | return self.a_page_links 146 | 147 | def format_date(self,datetime): 148 | datetime = datetime.split(" ") 149 | 150 | date = datetime[0].split("-") 151 | time = datetime[1] 152 | 153 | date[0] = date[0][:-2] 154 | month = { 155 | 'Jan':'01', 156 | 'Feb':'02', 157 | 'Mar':'03', 158 | 'Apr':'04', 159 | 'May':'05', 160 | 'Jun':'06', 161 | 'Jul':'07', 162 | 'Aug':'08', 163 | 'Sep':'09', 164 | 'Oct':'10', 165 | 'Nov':'11', 166 | 'Dec':'12' 167 | } 168 | date[1] = month[date[1]] 169 | date.reverse() 170 | date = '-'.join(date) 171 | final = date+" "+time 172 | return final 173 | 174 | 175 | -------------------------------------------------------------------------------- /moneycontrol.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import bs4 3 | import pytz 4 | 5 | SEARCH_URL = "http://www.moneycontrol.com/stocks/cptmarket/compsearchnew.php?search_data=&cid=&mbsearch_str=&topsearch_type=1&search_str=" 6 | PREFIX_URL = "http://www.moneycontrol.com" 7 | 8 | 9 | class MoneyControl(object): 10 | 11 | def __init__(self, ticker): 12 | 13 | # Declaring all the instance variable for the class 14 | self.ticker = ticker 15 | self.a = [] # Stores the announcements listed on the given page 16 | self.more_anno_link = "" # Link of the announcement page for the company 17 | self.more_news_link = "" # Link of news page for the company 18 | self.template_next_a_page = "" # For storing the link of the next page of the announcement 19 | self.a_page_links = [] # Stores the list of links all the announcement pages. 20 | self.link = "" # Link to the front page of the company we are looking for on moneycontrol 21 | self.present_a_page = 0 22 | 23 | self.fetch_ticker() 24 | self.__fetch_a_next_page_link() 25 | 26 | 27 | def fetch_ticker(self): 28 | try: 29 | self.link = SEARCH_URL+self.ticker 30 | r = requests.get(self.link) 31 | if r.status_code==200: 32 | print("Fetched page for ticker : "+self.ticker) 33 | # Creating a bs4 object to store the contents of the requested page 34 | self.soup = bs4.BeautifulSoup(r.content, 'html.parser') 35 | self.more_anno_link = PREFIX_URL + str(self.soup.find("div", attrs={"class":"PT5 gL_11", "align":"right"}).find("a")["href"] ) # class name extracted after looking at the document 36 | self.more_news_link = PREFIX_URL + str(self.soup.find("div", attrs={"class":"PT5 gL_11 FR"}).find("a")["href"]) 37 | elif r.status_code==404: 38 | print("Page not found") 39 | else: 40 | print("A different status code received : "+str(r.status_code)) 41 | 42 | except requests.ConnectionError as ce: 43 | print("There is a network problem (DNS Failure, refused connectionn etc.). Error : "+str(ce)) 44 | raise Exception 45 | 46 | except requests.Timeout as te: 47 | print("Request timed out. Error : "+str(te)) 48 | raise Exception 49 | 50 | except requests.TooManyRedirects as tmre: 51 | print("The request exceeded the maximum no. of redirections. Error : "+str(tmre)) 52 | raise Exception 53 | 54 | except requests. requests.exceptions.RequestException as oe: 55 | print("Any type of request related error : "+str(oe)) 56 | raise Exception 57 | 58 | 59 | def __fetch_a_next_page_link(self): 60 | 61 | # Fetches the template URL for fetching different announcement pages 62 | r = requests.get(self.more_anno_link) 63 | announcement_soup = bs4.BeautifulSoup(r.content, 'html.parser') 64 | # Checking whether the link for the next page is available or not 65 | if len(announcement_soup.find("div", attrs={"class":"gray2_11"}).find_all("a")) > 0: 66 | a = announcement_soup.find("div", attrs={"class":"gray2_11"}).find_all("a")[0]["href"] 67 | self.template_next_a_page = PREFIX_URL + a[0:-1] # Removing the page no. of the given link so that it becomes general link 68 | 69 | 70 | def fetch_a(self, page_no=1): 71 | 72 | if self.has_a(self.template_next_a_page + str(page_no)): 73 | 74 | # Clear all the previous data in "a" instance variable 75 | self.a = [] 76 | 77 | r = requests.get(self.template_next_a_page + str(page_no)) 78 | 79 | self.present_a_page = page_no 80 | 81 | announcement_soup = bs4.BeautifulSoup(r.content, 'html.parser') 82 | raw_links = announcement_soup.find_all("a", attrs={"class":"bl_15"}) 83 | 84 | # List of links of all the announcements on the given page 85 | list_of_links = [] 86 | for x in raw_links: 87 | link = PREFIX_URL + x['href'] 88 | list_of_links.append(link) 89 | a = requests.get(PREFIX_URL + x['href']) 90 | anno_page = bs4.BeautifulSoup(a.content, "html.parser") 91 | 92 | pdf_link = "" 93 | title = "" 94 | content = "" 95 | 96 | date = next(anno_page.find("p", attrs={"class":"gL_10"}).children) 97 | date = self.format_date(date) 98 | 99 | 100 | # Checking whether the title of the announcement is available or not 101 | if anno_page.find("span", attrs={"class":"bl_15"}): 102 | title = anno_page.find("span", attrs={"class":"bl_15"}).text 103 | 104 | # Checking whether content is available or not 105 | if anno_page.find("p", attrs={"class":"PT10 b_12"}): 106 | content = anno_page.find("p", attrs={"class":"PT10 b_12"}).text 107 | 108 | # Checking whether the PDF link is availableor not 109 | if anno_page.find("p", attrs={"class":"PT5"}).find("a"): 110 | pdf_link = PREFIX_URL + anno_page.find("p", attrs={"class":"PT5"}).find("a")["href"] 111 | 112 | 113 | anno = {"link":link, "pdf_link":pdf_link, "content":content, "title":title, "date":date} 114 | self.a.append(anno) 115 | 116 | else: 117 | self.a = [] 118 | 119 | return self.a 120 | 121 | 122 | def has_a(self, link): 123 | result = False 124 | r = requests.get(link) 125 | soup = bs4.BeautifulSoup(r.content, "html.parser") 126 | a = soup.find_all("p", attrs={"class":"gL_10"}) # Finding the list of the all the dates available on the page 127 | if len(a)>0: 128 | result = True 129 | 130 | return result 131 | 132 | 133 | def fetch_all_a_pages(self): 134 | i = 2 135 | # fetch the announcement on first page only when this instance variable is empty 136 | if self.template_next_a_page == "": 137 | self.fetch_a() 138 | link = self.template_next_a_page+str(i) 139 | while self.has_a(link): 140 | link = self.template_next_a_page+str(i) 141 | print("Page added : "+str(i)) 142 | self.a_page_links.append(link) 143 | i += 1 # Keep incrementing the value of i to check the next page 144 | return self.a_page_links 145 | 146 | def format_date(self,datetime): 147 | datetime = datetime.split(" ") 148 | 149 | date = datetime[0].split("-") 150 | time = datetime[1] 151 | 152 | date[0] = date[0][:-2] 153 | month = { 154 | 'Jan':'01', 155 | 'Feb':'02', 156 | 'Mar':'03', 157 | 'Apr':'04', 158 | 'May':'05', 159 | 'Jun':'06', 160 | 'Jul':'07', 161 | 'Aug':'08', 162 | 'Sep':'09', 163 | 'Oct':'10', 164 | 'Nov':'11', 165 | 'Dec':'12' 166 | } 167 | date[1] = month[date[1]] 168 | date.reverse() 169 | date = '-'.join(date) 170 | final = date+" "+time 171 | return final 172 | 173 | 174 | --------------------------------------------------------------------------------