8 |
9 |
28 |
29 |
--------------------------------------------------------------------------------
/gui.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, url_for, render_template, request, redirect
2 | from stories import *
3 | from getCookiesIG import *
4 | import json
5 | import os
6 | import threading
7 | import time
8 |
9 | scraper = Flask(__name__, static_folder='static')
10 | ## function to read json file, returns dict with file data
11 | def open_json(abs_filepath):
12 | try:
13 | with open(abs_filepath) as file:
14 | file_data = json.load(file)
15 | return file_data
16 | except Exception as e:
17 | print(e)
18 |
19 | @scraper.route("/")
20 | def landingPage():
21 | return render_template("index.html")
22 |
23 | @scraper.route("/enterParams")
24 | def enterParams():
25 | return render_template("searchParams.html")
26 |
27 | @scraper.route("/searchParams", methods=['POST'])
28 | def searchParams():
29 | username = request.form['username']
30 | pickle_file = username + ".pickle"
31 | userPass = request.form['pass']
32 | frequency = int(request.form['frequency'])
33 | userlst = request.files['userlst'].filename
34 |
35 | createJsonData(pickle_file,frequency,userlst)
36 |
37 | if not os.path.exists(pickle_file):
38 | if loginIG(username,userPass) == 0:
39 | ## Show error saying that login is unsuccessful
40 | return render_template("loginFailed.html")
41 |
42 |
43 | ## Should display an empty map here
44 | return render_template("map.html", freq=frequency, data="")
45 |
46 | @scraper.route("/startScraping", methods=['POST'])
47 | def startScrape():
48 | print("Inside")
49 | thread = threading.Thread(target=startScraping)
50 | thread.start()
51 | return ''
52 |
53 | @scraper.route("/selectPreviousJSON")
54 | def selectPreviousJSON():
55 | return render_template("previous.html")
56 |
57 | @scraper.route("/loadSearch", methods=['POST'])
58 | def loadSearch():
59 | ## To implement load map and running search in the background
60 | fileName = request.files['jsonFile'].filename
61 | data = open_json(fileName)
62 | frequency = data[0]["parameters"]["frequency"]
63 | return render_template(
64 | "map.html", freq = frequency,
65 | data=data[1]
66 | )
67 |
68 | @scraper.route("/map")
69 | def mapView():
70 | data = open_json('data.json')
71 | return render_template(
72 | "map.html",
73 | data=data[1]
74 | )
75 |
76 | def createJsonData(pickle_file,frequency,userlst):
77 | data = [{"parameters": {"pickle_file":pickle_file,"frequency":frequency,"users_file":userlst}},{}]
78 | with open('data.json', 'w') as f:
79 | json.dump(data, f, indent=4)
80 |
81 | if __name__ == "__main__":
82 | scraper.run()
--------------------------------------------------------------------------------
/getCookiesIG.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | from time import sleep
3 | from datetime import datetime
4 |
5 | from selenium import webdriver
6 | from selenium.webdriver.support.ui import WebDriverWait
7 | from selenium.webdriver.support import expected_conditions as EC
8 | from selenium.common.exceptions import TimeoutException
9 | from selenium.webdriver.common.by import By
10 | from selenium.webdriver.firefox.options import Options as FirefoxOptions
11 | from selenium.webdriver.firefox.service import Service as FirefoxService
12 | from webdriver_manager.firefox import GeckoDriverManager
13 |
14 | def loginIG(username,password):
15 | options = FirefoxOptions()
16 | options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36')
17 |
18 | if not username or not password:
19 | return(0)
20 | driver = webdriver.Firefox(options=options,service=FirefoxService(GeckoDriverManager().install()))
21 | website = (f'https://www.instagram.com/accounts/login/?next=%2Flogin%2F&source=desktop_nav')
22 |
23 | driver.get(website)
24 | driver.maximize_window()
25 |
26 | try:
27 | WebDriverWait(driver,8).until(EC.presence_of_element_located((By.NAME,'username')))
28 | sleep(2)
29 | except TimeoutException:
30 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Could not load Instagram; please check your Internet connection')
31 | driver.quit()
32 | return(0)
33 |
34 | try:
35 | driver.find_element(By.NAME,'username').send_keys(username)
36 | sleep(1)
37 | driver.find_element(By.NAME,'password').send_keys(password)
38 | sleep(1)
39 | driver.find_element(By.XPATH,'//*[@id="loginForm"]/div/div[3]/button').click() #login btn
40 | except Exception as e:
41 | print(f'Did not manage to login - {e}')
42 | driver.quit()
43 | return(0)
44 | try:
45 | ## Wait until profile button is present before continuing
46 | WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div/div/div[2]/div[8]/div/div/a/div')))
47 | except TimeoutException:
48 | try:
49 | ## Wait until "more" button is present before continuing
50 | WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div[2]/section/main/div/div/div/section/div/button')))
51 | except TimeoutException:
52 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Failed to save cookies file; check login details.')
53 | driver.quit()
54 | return(0)
55 |
56 | ## Opens a file named 'cookies.pickle' and saves the cookies from the driver into the pickle file
57 | with open(f'{username}.pickle', 'wb') as file:
58 | pickle.dump(driver.get_cookies(),file)
59 |
60 | driver.quit()
61 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Cookies saved successfully.')
62 | return(1)
63 |
64 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Instagram Story Visualiser
2 |
3 | ## Team Members
4 | 1) Lim Zhen Guang
5 | 2) Lam Wei Ern
6 |
7 | ## Tool Description
8 | Currently, it is difficult for researchers to monitor large amounts of data, especially those that have a expiry element to them based on time (e.g., Instagram Story). It is also difficult for researchers to monitor events across the world and correlate data visually.
9 |
10 | This tool uses an Instagram account to monitor the Instagram Story of a user-defined list of Instagram users. The tool will periodically scrape these users based on user-defined time intervals. During the scraping, it will download the media posted on the Instagram Story, along with any location tag in the Story. After the scraping, it will store the data in a json file which is read by the Front-end website that is hosted on Python Flask. The Python Flask website will display a map and a timeline slider. The map will contain pins that represent each Instagram Story that was scraped and contains location data. The timeline slider will allow the user to view Instagram Stories that were scraped for that day, allowing users to visualize stories on a map. Stories that were scraped but do not have location tag will also be displayed on the website.
11 |
12 | ## Installation Guide:
13 | 1) Ensure that you minimally have Python version>=3.9.7
14 | 1. git clone https://github.com/Jasawn/python-instagram-story-visualiser
15 | 2. cd python-instagram-story-visualiser
16 | 3. pip install -r requirements.txt
17 |
18 | ## Usage
19 | (Starting New Scrape)
20 | Step 1: Open CMD and change the directory to where the code was saved and run the following code
21 | python gui.py
22 |
23 | 
24 |
25 | Step 2: Copy the link as shown in the image above 'http://127.0.0.1:5000/' and paste into a browser (Preferably Chrome or Firefox) and the output will be as shown in the screenshot below
26 | 
27 |
28 | Step 3: Click on 'Click here to start new search' to begin Instagram Story Scraping with the defined list of users. After clicking on the 'Click here to start new search', the output will be as shown in the screenshot below.
29 | 
30 |
31 | **NOTE:** Do provide valid Instagram account. Create a text file with predefined list of users specified inside the text file and save the file in the same directory as the code.
32 |
33 | 
34 |
35 | Step 4: After entering the required information, click on 'Start Scraping...' and let it load. Initially, another browser will open another tab to attempt to login in Instagram. Next, the output will be as shown in the screenshot below.
36 | 
37 |
38 | **NOTE:** While there will be a browser popup, you can minimise the browser and continue with your daily tasks.
39 |
40 | Step 5: After the scraping has been completed, a 'data.json' file will be created in the directory and the content downloaded will be saved in /static directory. The browser will automatically reload and show the data scraped from the defined list of user as shown in the image below.
41 |
42 | 
43 |
44 | **NOTE:** Those stories that have a location tag will have a pin shown in the map. While those stories without location tag can be seen after clicking on the 'No Coordinates' button located near the timeline slider
45 |
46 | Step 6: Clicking on the pin will have the output as shown in the screenshot below.
47 | 
48 |
49 | **NOTE:** The popup consists of the date that the story is being posted, the user that the story was scraped from, the location tag and the exact timing of the story that is posted.
50 |
51 | Step 7: Clicking on the 'No Coordinates' button will have the output as shown in the screenshot below.
52 | 
53 |
54 | **NOTE:** The video is playable
55 |
56 | (Load previous data)
57 | Step 1: Open CMD and change the directory to where the code was saved and run the following code
58 | python gui.py
59 |
60 | 
61 |
62 | Step 2: Copy the link as shown in the image above 'http://127.0.0.1:5000/' and paste into a browser (Preferably Chrome or Firefox) and the output will be as shown in the screenshot below
63 | 
64 |
65 | Step 3: Click on 'Click here to load previous searches
66 | 
67 |
68 | Step 4: Choose 'data.json' to load the data that was scraped previously and click on 'Load JSON File...'
69 | 
70 |
71 | Step 5: The browser will be redirected to a map with a timeline slider
72 | 
73 | 
74 | 
75 |
76 | **NOTE:** Move the slider to view the contents for the day
77 |
78 | ## Additional Information
79 | Pros:
80 | - Instagram Story media is downloaded and stored locally so that they can be archived and collected for other purposes.
81 | - Users are able to leave the application running unsupervised to collect information on stories and return at at future time to investigate the data.
82 | - Application can use any profile to monitor accounts, and even monitor private profiles as long as the logged-in account is following the private account. This can allow operators to use the application to monitor profiles they do not typically have access to.
83 |
84 | Cons:
85 | - Application relies heavily on web scraping; a change in website layout will result in the app breaking.
86 | - Currently only supports scraping of Instagram Stories.
87 | - Instagram Stories must have a Location Tag, otherwise it will not be displayed on a map.
88 | - Map is unable to auto-refresh once a scrape has completed
89 | - Unable to scrape after loading previous version of JSON file
90 |
91 | Roadmap:
92 | - Figure out how to parse the content of the JSON file into the scraper so that it can continue to scrape while loading previous versions of JSON file
93 | - Figure out how to auto-refresh the map with updated data once scraping has completed.
94 | - Look for other methods to monitor Instagram profiles and download the Instagram Story data.
95 | - Allow monitoring of Tiktok stories, Snapchat, Facebook etc.
96 | - Allow operators to create "Versions" of scraping, allowing customization of which users' stories to display on the map depending on the topic being investigated
97 | - Provide graph/chart and perform some analytics on the amount of data collected and analyze trends
98 |
99 |
--------------------------------------------------------------------------------
/templates/map.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Map
7 |
8 |
9 |
10 |
11 |
12 |
93 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
375 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/stories.py:
--------------------------------------------------------------------------------
1 | from selenium.webdriver.support.ui import WebDriverWait
2 | from selenium.webdriver.support import expected_conditions as EC
3 | from selenium.common.exceptions import ElementClickInterceptedException, TimeoutException, NoSuchElementException
4 |
5 | from selenium import webdriver
6 | from selenium.webdriver.common.by import By
7 | from selenium.webdriver.common.keys import Keys
8 | from selenium.webdriver.firefox.options import Options as FirefoxOptions
9 | from selenium.webdriver.firefox.service import Service as FirefoxService
10 | from webdriver_manager.firefox import GeckoDriverManager
11 |
12 |
13 | import os
14 | from random import randint, shuffle
15 | from time import sleep
16 | from datetime import datetime, timedelta, timezone
17 | import pickle
18 | import requests
19 | import json
20 |
21 | py_filepath = os.getcwd()
22 | archive_filepath = py_filepath+'\\archive\\'
23 |
24 | list_of_stories = []
25 | jsonData = []
26 | cwd = os.getcwd()
27 |
28 | start_time = ""
29 | end_time = ""
30 |
31 | def skipStory(driver):
32 | ## continue to the next story by finding the right arrow
33 | print('Skipping story . . .')
34 | if driver.find_element(By.XPATH,'/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/button').get_attribute('aria-label') == 'Next':
35 | driver.find_element(By.XPATH,'/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/button').click()
36 | else:
37 | driver.find_element(By.XPATH,'/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/button[2]').click()
38 |
39 | def pauseStory(driver):
40 | ## pause the stories from loading
41 | try:
42 | ## check if the aria-label of the button is Pause or Play
43 | ## if it is Play, means it is currently paused; hence do nothing
44 | ## else if it is Pause, it will throw TimeoutException
45 | WebDriverWait(driver,3).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/header/div[2]/div[2]/button[1]/div/*[name()="svg"][@aria-label="Play"]')))
46 | except TimeoutException as e:
47 | ## click on the button to pause the video
48 | driver.find_element(By.XPATH,"/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/header/div[2]/div[2]/button[1]/div").click()
49 |
50 | def locationToLonLat(address):
51 |
52 | user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
53 | api = f'https://nominatim.openstreetmap.org/search.php?q={address.replace(" ", "+")}&format=jsonv2&limit=1'
54 |
55 | try:
56 | r = requests.get(api,headers=user_agent)
57 | data = json.loads(r.text)
58 |
59 | return [float(data[0]["lon"]),float(data[0]["lat"])]
60 | except Exception as e:
61 | return [None,None]
62 |
63 | def readJsonData(fn):
64 | with open(fn,'r') as f:
65 | return json.load(f)
66 |
67 | def saveJsonData(fn, data, new_data):
68 | t = {}
69 | for obj in new_data:
70 |
71 | dt = datetime.strptime(obj['time'], '%Y-%m-%dT%H:%M:%S.%fZ').strftime("%d-%m-%Y")
72 | if dt in t:
73 | t[dt].append(obj)
74 | else:
75 | t[dt] = [obj]
76 |
77 | for dt in t:
78 | ## {"dt":[obj,obj], "dt2":[obj2,obj3]}
79 | if dt not in data[1]:
80 | ## if there is no data, add it
81 | data[1][dt] = t[dt]
82 | else:
83 | ## if there is data, append it
84 | data[1][dt] += t[dt]
85 |
86 | with open(fn,'w',encoding='utf-8') as f:
87 | json.dump(data,f,indent=4)
88 |
89 | def convert_to_unix_time(date_string):
90 | dt = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
91 | return int(dt.timestamp())
92 |
93 | def downloadStories(list_of_stories):
94 | cwd = os.getcwd()
95 | temp = []
96 |
97 | for obj in list_of_stories:
98 | user = obj['username']
99 |
100 | static_filepath = f'{cwd}\\static'
101 |
102 | ## check if the folder to store data exists
103 | ## if not, create the "static" folder
104 | ## saving the file based on the user and date of story posted
105 | if not os.path.exists(static_filepath):
106 | os.makedirs(static_filepath)
107 |
108 | try:
109 | print(f"Downloading from {obj['download_url']}")
110 | r = requests.get(obj['download_url'])
111 | if r.status_code == 200:
112 |
113 | filename = f"{user}_{convert_to_unix_time(obj['time'])}"
114 |
115 | if obj['type'] == 'image':
116 | filename+='.jpg'
117 | else:
118 | filename+='.mp4'
119 |
120 | full_filepath = f'{static_filepath}\\{filename}'
121 | with open(full_filepath,'wb') as f:
122 | f.write(r.content)
123 | print(f'Downloaded story to {full_filepath}')
124 |
125 | obj['filename'] = filename
126 | else:
127 | print(f'Failed to download file')
128 | obj['filename'] = 'error'
129 |
130 | except Exception as e:
131 | print(e)
132 | obj['filename'] = 'error'
133 |
134 | temp.append(obj)
135 |
136 | return temp
137 |
138 |
139 | ## function to find location tag
140 | def find_dialog_element(elements):
141 | for element in elements:
142 | if element.get_attribute("role") == "dialog":
143 | return element
144 | else:
145 | children = element.find_elements(By.CSS_SELECTOR,"*")
146 | if children:
147 | dialog_element = find_dialog_element(children)
148 | if dialog_element:
149 | return dialog_element
150 | return None
151 |
152 |
153 | ## get list of network requests made by a driver then clear the existing requests
154 | ## looks through the list of network requests to find the request
155 | ## to the video resource indicated by "&bytestart=0" in the request
156 | def getDownloadURLFromRequests(driver):
157 | network_logs = driver.execute_script("""
158 | var performance = window.performance || window.webkitPerformance || window.mozPerformance || window.msPerformance || {};
159 | var network = performance.getEntriesByType("resource");
160 | return network;
161 | """)
162 | driver.execute_script("window.performance.clearResourceTimings();")
163 |
164 | for log in network_logs:
165 | url = log['name']
166 | if '&bytestart=0' in url:
167 | return url.split('&bytestart=0')[0]
168 |
169 |
170 | def scrapeStories(user_list, driver):
171 |
172 | global start_time
173 | global list_of_stories
174 | global end_time
175 |
176 | start_time = datetime.now()
177 |
178 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Program start at ' + start_time.strftime('%d %b %y %H:%M:%Shrs'))
179 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Scraping for stories since ' + end_time.strftime('%d %b %y %H:%M:%Shrs'))
180 |
181 | ## get list of urls to stories page of profiles
182 | list_of_profiles = [f"https://www.instagram.com/stories/{user}" for user in user_list]
183 |
184 | ## shuffle list of profiles to randomize scraping order
185 | ## shuffle(list_of_profiles)
186 |
187 | list_of_stories = []
188 |
189 | ## stories checker
190 | for url in list_of_profiles:
191 |
192 | location_count = 0
193 | story_count = 0
194 |
195 | ## opens the page of the instagram profile to be scraped
196 | ## to handle in try/except
197 | driver.get(url)
198 |
199 | try:
200 | view_story_xpath = "/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div[3]/div"
201 | WebDriverWait(driver,8).until(EC.presence_of_element_located((By.XPATH, view_story_xpath)))
202 | driver.find_element(By.XPATH, view_story_xpath).click()
203 | except TimeoutException:
204 | try:
205 | view_story_xpath2 = "/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div[3]/div"
206 | WebDriverWait(driver,8).until(EC.presence_of_element_located((By.XPATH, view_story_xpath)))
207 | driver.find_element(By.XPATH, view_story_xpath2).click()
208 | except Exception as e:
209 | print(e)
210 | return
211 | try:
212 | print(f'Found stories from {url[34:]}')
213 |
214 | while "stories" in driver.current_url:
215 |
216 | ## pause the story to prevent it from loading
217 | pauseStory(driver)
218 |
219 | ## get timestamp of current story to check if it is still within scrape time
220 | timestamp_xpath = '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/header/div[2]/div[1]/div/div/div/div/time'
221 | story_timestamp = driver.find_element(By.XPATH, timestamp_xpath).get_attribute("datetime") #2023-04-21T12:46:12.000Z
222 | story_timestamp_obj = datetime.strptime(story_timestamp,"%Y-%m-%dT%H:%M:%S.%fZ")
223 | story_timestamp_gmt = story_timestamp_obj + timedelta(minutes=480)
224 |
225 | if story_timestamp_gmt >= end_time:
226 | ## means that story was posted after the last scrape
227 | ## hence we should process the story
228 | print(f'Processing story - {story_timestamp}')
229 | story_count += 1
230 |
231 | else:
232 | skipStory(driver)
233 | continue
234 |
235 | obj = {"username":url[34:]}
236 | obj["time"] = story_timestamp
237 | ## initialize location, lon and lat as empty first
238 | obj["location_name"] = ""
239 | obj["lon"] = None
240 | obj["lat"] = None
241 | obj["ig_location_url"] = ""
242 |
243 | ## check if story is an image or video
244 | try:
245 | img_src_element = '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/img'
246 | WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, img_src_element)))
247 | download_url = driver.find_element(By.XPATH,img_src_element).get_attribute("src")
248 | print(f'IMAGE - {download_url}')
249 | obj["type"] = "image"
250 | obj["download_url"] = download_url
251 | except TimeoutException:
252 | download_url = getDownloadURLFromRequests(driver)
253 | print(f'VIDEO - {download_url}')
254 | obj["type"] = "video"
255 | obj["download_url"] = download_url
256 |
257 | ## if there is a location tag in the story, location_tag will be the xpath of the tag
258 | location_tag = False
259 |
260 | xpaths = [
261 | '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div/div[2]/div/div',
262 | '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div/div/div/div/div/div/div/div[2]/div[1]/div'
263 | ]
264 |
265 | ## depending on the story (video vs static image)
266 | ## the xpath of the location tag will be different
267 | ## hence do some checks to find the correct xpath
268 | ## instead of XPATH, consider searching for aria-label="Cancel Pop-up" and looking for the first child element which is the location tag
269 |
270 | for xpath in xpaths:
271 | ## once the correct location tag is found, break out of the loop
272 | try:
273 | WebDriverWait(driver,3).until(EC.presence_of_element_located((By.XPATH, xpath)))
274 | location_tag = xpath
275 | location_count+=1
276 | break
277 | except TimeoutException:
278 | pass
279 |
280 | ## if location tag is false, skip the story
281 | if not location_tag:
282 | skipStory(driver)
283 | list_of_stories.append(obj) ## no location_name, lon,lat,igloc
284 | continue
285 |
286 | ## click on the location tag
287 | location_tag_elem = driver.find_element(By.XPATH, location_tag)
288 | driver.execute_script("arguments[0].click();", location_tag_elem)
289 | sleep(randint(1,2))
290 |
291 | ## find the "See Location" tag and click on it
292 | xp = '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div/div/div/div/div/div/div/div[2]'
293 | element_list = driver.find_elements(By.XPATH,xp)
294 |
295 | if not element_list:
296 | xp2 = '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div/div[2]'
297 | element_list = driver.find_elements(By.XPATH,xp2)
298 |
299 | dialog_elem = find_dialog_element(element_list)
300 | dialog_elem.click()
301 |
302 | try:
303 | location_name_tag = '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/article/header/div[2]/div/div/span'
304 | WebDriverWait(driver,15).until(EC.presence_of_element_located((By.XPATH, location_name_tag)))
305 | ig_location_url = driver.current_url
306 | location_name = driver.find_element(By.XPATH,location_name_tag).text
307 | lon_and_lat = locationToLonLat(location_name)
308 |
309 | obj["location_name"] = location_name
310 | obj["lon"] = lon_and_lat[0]
311 | obj["lat"] = lon_and_lat[1]
312 | obj["ig_location_url"] = ig_location_url
313 |
314 | driver.back()
315 | sleep(2)
316 |
317 | except TimeoutException as TE:
318 | print(TE)
319 |
320 | list_of_stories.append(obj)
321 |
322 | skipStory(driver)
323 |
324 | print(f'Finished scraping {url[34:]} . . . Moving on to next profile . . .')
325 | print(f'Number of stories found: {story_count}')
326 | print(f'Number of stories with location tag found: {location_count}')
327 |
328 | except TimeoutException as TE:
329 | try:
330 | ## check if the "Sorry, this page isn't available." div exists which means the profile is invalid
331 | sorry_xpath = '/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/div/span'
332 | driver.find_element(By.XPATH, sorry_xpath)
333 | print(f'The profile {url[34:]} does not exist')
334 |
335 | except NoSuchElementException as NSE:
336 | print(f'No stories from {url[34:]}')
337 |
338 | continue
339 |
340 | print('Finished scraping all profiles . . .')
341 |
342 | try:
343 | test = driver.execute_script("var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;")
344 | with open('requests.txt','w',encoding='utf-8') as f:
345 | json.dump(test, f, indent=4)
346 | except:
347 | pass
348 |
349 | driver.quit()
350 |
351 |
352 | def startBrowser():
353 | options = FirefoxOptions()
354 | options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36')
355 | driver = webdriver.Firefox(options=options,service=FirefoxService(GeckoDriverManager().install()))
356 | driver.maximize_window()
357 | return driver
358 |
359 |
360 | def loginInstagram(filename, driver): ## need to handle exceptions ie. return or quit
361 | try:
362 | driver.get('https://www.instagram.com/')
363 |
364 | ## takes in filename of cookie file and driver
365 | cookies = pickle.load(open(filename, "rb"))
366 | for cookie in cookies:
367 | driver.add_cookie(cookie)
368 |
369 | driver.refresh()
370 |
371 | WebDriverWait(driver,8).until(EC.presence_of_element_located((By.XPATH,'/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div/div/div[2]/div[8]/div/div/a/div')))
372 | except FileNotFoundError as fnfe:
373 | print(f'Unable to find pickles file - {fnfe}')
374 | except TimeoutException as e:
375 | print(f'Failed to login - {e}')
376 |
377 |
378 | def getListOfUsers(filename):
379 | ## reads list of instagram profiles to scrape from
380 | try:
381 | with open(filename) as users_file:
382 | ## returns a List containing IG profile URLs and strips of \n at the back
383 | return [line.strip() for line in users_file]
384 | except FileNotFoundError as FNFE:
385 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - "igprofiles.txt" not found - {FNFE}')
386 | return
387 |
388 | def startScraping():
389 | global start_time
390 | global end_time
391 |
392 | counter = 0
393 | end_time = ""
394 |
395 | while True:
396 | start_time = datetime.now()
397 | jsonData = readJsonData('data.json')
398 |
399 | frequency = jsonData[0]['parameters']['frequency']
400 | users_file = jsonData[0]['parameters']['users_file']
401 | pickle_file = jsonData[0]['parameters']['pickle_file']
402 | ## First iteration of scraping
403 | if counter == 0:
404 | end_time = start_time - timedelta(minutes=frequency)
405 |
406 | driver = startBrowser()
407 | list_of_users = getListOfUsers(users_file)
408 | loginInstagram(filename=pickle_file, driver=driver)
409 | scrapeStories(user_list=list_of_users, driver=driver)
410 |
411 | temp = downloadStories(list_of_stories=list_of_stories) #download the files and return new list of objects
412 |
413 | saveJsonData('data.json',jsonData, temp)
414 |
415 | end_time = datetime.now()
416 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Program end at ' + end_time.strftime('%d %b %y %H:%M:%Shrs'))
417 |
418 | sleepTime = round(((start_time + timedelta(minutes=frequency)) - end_time).total_seconds())
419 |
420 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Sleeping until ' + (end_time + timedelta(seconds=sleepTime)).strftime(('%d %b %y %H:%M:%Shrs')))
421 | print(f'{datetime.now().strftime("%d %b %y %H:%M:%S")} - Sleeping...\n')
422 |
423 | sleep(sleepTime)
424 | counter += 1
425 |
426 |
427 |
428 |
--------------------------------------------------------------------------------