Class: Forki::PostScraper
- Defined in:
- lib/forki/scrapers/post_scraper.rb
Overview
rubocop:disable Metrics/ClassLength
Instance Method Summary collapse
- #check_if_post_is_image(graphql_objects) ⇒ Object
- #check_if_post_is_in_comment_stream(graphql_objects) ⇒ Object
- #check_if_post_is_reel(graphql_object) ⇒ Object
- #check_if_post_is_video(graphql_objects) ⇒ Object
-
#extract_image_post_data(graphql_object_array) ⇒ Object
Extracts data from an image post by parsing GraphQL strings as seen in the video post scraper above.
-
#extract_live_video_post_data_from_watch_page(graphql_strings) ⇒ Object
Extract data from live video post on the watch page.
- #extract_post_data(graphql_strings) ⇒ Object
-
#extract_reaction_counts(reactions_object) ⇒ Object
Returns a hash containing counts of each reaction to a post Takes the edges list and creates a dictionary for each element that looks like: 1234 Then merges the dictionaries with the inject call.
- #extract_video_comment_post_data(graphql_objects) ⇒ Object
-
#extract_video_post_data(graphql_strings) ⇒ Object
Unfortunately, there’s a taxonomy of video post types, all of which require different parsing methods Specifically, there are normal video posts, video posts from the watch page, and live video posts from the watch page The general strategy for extracting information from each type, though, is to find which of the 30-odd GraphQL strings are relevant After finding those GraphQL strings, we parse them into hashes and extract the information we need.
- #extract_video_post_data_alternative(graphql_object_array) ⇒ Object
-
#extract_video_post_data_from_watch_page(graphql_strings) ⇒ Object
Extract data from a non-live video post on the watch page.
-
#find_number_of_views ⇒ Object
Searches the DOM to finds the number of times a (video) post has been viewed.
- #get_graphql_objects(graphql_strings) ⇒ Object
- #is_post_available? ⇒ Boolean
-
#parse(url) ⇒ Object
Uses GraphQL data and DOM elements to collect information about the current post.
- #take_screenshot ⇒ Object
Methods inherited from Scraper
#download_image, #find_graphql_data_closure_index, #find_graphql_data_strings, #initialize
Constructor Details
This class inherits a constructor from Forki::Scraper
Instance Method Details
#check_if_post_is_image(graphql_objects) ⇒ Object
63 64 65 66 67 68 |
# File 'lib/forki/scrapers/post_scraper.rb', line 63 def check_if_post_is_image(graphql_objects) graphql_objects.any? do |graphql_object| # if any GraphQL objects contain the top-level keys above, return true true unless graphql_object.fetch("image", nil).nil? # so long as the associated values are not nil true unless graphql_object.fetch("currMedia", nil).nil? end end |
#check_if_post_is_in_comment_stream(graphql_objects) ⇒ Object
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/forki/scrapers/post_scraper.rb', line 70 def check_if_post_is_in_comment_stream(graphql_objects) graphql_objects.find do |graphql_object| next unless graphql_object.key?("nodes") begin type = graphql_object["nodes"].first["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"]["media"]["__typename"] rescue StandardError # if there's an error just return false, since the structure is so specific checking the whole thing is a lot next end return true if type == "Video" end false end |
#check_if_post_is_reel(graphql_object) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/forki/scrapers/post_scraper.rb', line 51 def check_if_post_is_reel(graphql_object) return false unless graphql_object.key?("node") begin style_infos = graphql_object["node"]["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"]["style_infos"].first rescue NoMethodError # if the object doesn't match the attribute chain above, the line above will try to operate on nil return false end style_infos.include?("fb_shorts_story") end |
#check_if_post_is_video(graphql_objects) ⇒ Object
47 48 49 |
# File 'lib/forki/scrapers/post_scraper.rb', line 47 def check_if_post_is_video(graphql_objects) graphql_objects.any? { |graphql_object| graphql_object.key?("is_live_streaming") || graphql_object.key?("video") || check_if_post_is_reel(graphql_object) } end |
#extract_image_post_data(graphql_object_array) ⇒ Object
Extracts data from an image post by parsing GraphQL strings as seen in the video post scraper above
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/forki/scrapers/post_scraper.rb', line 222 def extract_image_post_data(graphql_object_array) graphql_object_array.find { |graphql_object| graphql_object.key?("viewer_actor") && graphql_object.key?("display_comments") } curr_media_object = graphql_object_array.find { |graphql_object| graphql_object.key?("currMedia") } creation_story_object = graphql_object_array.find { |graphql_object| graphql_object.key?("creation_story") && graphql_object.key?("message") } feedback_object = graphql_object_array.find { |graphql_object| graphql_object.has_key?("comet_ufi_summary_and_actions_renderer") }["comet_ufi_summary_and_actions_renderer"]["feedback"] share_count_object = feedback_object.fetch("share_count", {}) poster = creation_story_object["creation_story"]["comet_sections"]["actor_photo"]["story"]["actors"][0] reaction_counts = extract_reaction_counts(feedback_object["cannot_see_top_custom_reactions"]["top_reactions"]) post_details = { id: curr_media_object["currMedia"]["id"], num_comments: feedback_object["comments_count_summary_renderer"]["feedback"]["total_comment_count"], num_shares: share_count_object.fetch("count", nil), reshare_warning: feedback_object["should_show_reshare_warning"], image_url: curr_media_object["currMedia"]["image"]["uri"], text: (creation_story_object["message"] || {}).fetch("text", nil), profile_link: poster["url"], created_at: curr_media_object["currMedia"]["created_time"], has_video: false } post_details[:image_file] = Forki.retrieve_media(post_details[:image_url]) post_details[:reactions] = reaction_counts post_details end |
#extract_live_video_post_data_from_watch_page(graphql_strings) ⇒ Object
Extract data from live video post on the watch page
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/forki/scrapers/post_scraper.rb', line 280 def extract_live_video_post_data_from_watch_page(graphql_strings) creation_story_object = JSON.parse(graphql_strings.find { |graphql| (graphql.include? "comment_count") && \ (graphql.include? "creation_story") })["video"]["creation_story"] media_object = JSON.parse(graphql_strings.find { |graphql| graphql.include? "playable_url" })["video"]["creation_story"]["attachments"][0]["media"] video_permalink = creation_story_object["shareable"]["url"].delete("\\") reaction_counts = extract_reaction_counts(creation_story_object["feedback_context"]["feedback_target_with_context"]["cannot_see_top_custom_reactions"]["top_reactions"]) post_details = { id: creation_story_object["shareable"]["id"], num_comments: creation_story_object["feedback_context"]["feedback_target_with_context"]["total_comment_count"], num_shares: nil, num_views: find_number_of_views, # as far as I can tell, this is never present for live videos reshare_warning: creation_story_object["feedback_context"]["feedback_target_with_context"]["should_show_reshare_warning"], video_preview_image_url: creation_story_object["attachments"][0]["media"]["preferred_thumbnail"]["image"]["uri"], video_url: (media_object.fetch("playable_url_quality_hd", nil) || media_object.fetch("playable_url", nil)).delete("\\"), text: creation_story_object["attachments"][0]["media"]["savable_description"]["text"], created_at: creation_story_object["attachments"][0]["media"]["publish_time"], profile_link: video_permalink[..video_permalink.index("/videos")], has_video: true } post_details[:video_preview_image_file] = Forki.retrieve_media(post_details[:video_preview_image_url]) post_details[:video_file] = Forki.retrieve_media(post_details[:video_url]) post_details[:reactions] = reaction_counts post_details end |
#extract_post_data(graphql_strings) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/forki/scrapers/post_scraper.rb', line 20 def extract_post_data(graphql_strings) # Bail out of the post otherwise it gets stuck raise ContentUnavailableError unless is_post_available? graphql_objects = get_graphql_objects(graphql_strings) post_has_video = check_if_post_is_video(graphql_objects) post_has_image = check_if_post_is_image(graphql_objects) # There's a chance it may be embedded in a comment chain like this: # https://www.facebook.com/PlandemicMovie/posts/588866298398729/ post_has_video_in_comment_stream = check_if_post_is_in_comment_stream(graphql_objects) if post_has_video == false if post_has_video extract_video_post_data(graphql_strings) elsif post_has_video_in_comment_stream extract_video_comment_post_data(graphql_objects) elsif post_has_image extract_image_post_data(graphql_objects) else raise UnhandledContentError end end |
#extract_reaction_counts(reactions_object) ⇒ Object
Returns a hash containing counts of each reaction to a post Takes the edges list and creates a dictionary for each element that looks like: 1234 Then merges the dictionaries with the inject call
310 311 312 313 314 315 316 |
# File 'lib/forki/scrapers/post_scraper.rb', line 310 def extract_reaction_counts(reactions_object) reactions_object["edges"].map do |reaction| { "num_#{reaction["node"]["localized_name"].downcase}s".to_sym => reaction["reaction_count"] } end.inject { |emoji_counts, count| emoji_counts.merge(count) } end |
#extract_video_comment_post_data(graphql_objects) ⇒ Object
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/forki/scrapers/post_scraper.rb', line 102 def extract_video_comment_post_data(graphql_objects) graphql_nodes = nil graphql_objects.find do |graphql_object| next unless graphql_object.key?("nodes") graphql_nodes = graphql_object["nodes"] break end media = graphql_nodes.first["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"]["media"] inital_feedback_object = graphql_nodes.first["comet_sections"]["feedback"]["story"]["feedback_context"]["feedback_target_with_context"]["ufi_renderer"]["feedback"] feedback_object = inital_feedback_object["comet_ufi_summary_and_actions_renderer"]["feedback"] post_details = { id: media["id"], num_comments: feedback_object["comment_count"]["total_count"], num_shares: feedback_object["share_count"]["count"], num_views: feedback_object["video_view_count"], reshare_warning: feedback_object["should_show_reshare_warning"], video_preview_image_url: media["preferred_thumbnail"]["image"]["uri"], video_url: media["playable_url_quality_hd"] || media["playable_url"], text: graphql_nodes.first["comet_sections"]["content"]["story"]["comet_sections"]["message"]["story"]["message"]["text"], created_at: media["publish_time"], profile_link: graphql_nodes.first["comet_sections"]["context_layout"]["story"]["comet_sections"]["actor_photo"]["story"]["actors"].first["url"], has_video: true } post_details[:video_preview_image_file] = Forki.retrieve_media(post_details[:video_preview_image_url]) post_details[:video_file] = Forki.retrieve_media(post_details[:video_url]) post_details[:reactions] = inital_feedback_object["comet_ufi_summary_and_actions_renderer"]["feedback"]["i18n_reaction_count"] post_details end |
#extract_video_post_data(graphql_strings) ⇒ Object
Unfortunately, there’s a taxonomy of video post types, all of which require different parsing methods Specifically, there are normal video posts, video posts from the watch page, and live video posts from the watch page The general strategy for extracting information from each type, though, is to find which of the 30-odd GraphQL strings are relevant After finding those GraphQL strings, we parse them into hashes and extract the information we need
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/forki/scrapers/post_scraper.rb', line 139 def extract_video_post_data(graphql_strings) unless all("h1").find { |h1| h1.text.strip == "Watch" }.nil? return extract_video_post_data_from_watch_page(graphql_strings) # If this is a "watch page" video end graphql_object_array = graphql_strings.map { |graphql_string| JSON.parse(graphql_string) } story_node_object = graphql_object_array.find { |graphql_object| graphql_object.key? "node" }&.fetch("node", nil) # user posted video story_node_object = story_node_object || graphql_object_array.find { |graphql_object| graphql_object.key? "nodes" }&.fetch("nodes")&.first # page posted video return extract_video_post_data_alternative(graphql_object_array) if story_node_object.nil? if story_node_object["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"].key?("media") video_object = story_node_object["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"]["media"] creation_date = video_object["publish_time"] # creation_date = video_object["video"]["publish_time"] elsif story_node_object["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"].key?("style_infos") # For "Reels" we need a separate way to parse this video_object = story_node_object["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"]["style_infos"].first["fb_shorts_story"]["short_form_video_context"]["playback_video"] creation_date = story_node_object["comet_sections"]["content"]["story"]["attachments"].first["styles"]["attachment"]["style_infos"].first["fb_shorts_story"]["creation_time"] else raise "Unable to parse video object" end feedback_object = story_node_object["comet_sections"]["feedback"]["story"]["feedback_context"]["feedback_target_with_context"]["ufi_renderer"]["feedback"] reaction_counts = extract_reaction_counts(feedback_object["comet_ufi_summary_and_actions_renderer"]["feedback"]["cannot_see_top_custom_reactions"]["top_reactions"]) share_count_object = feedback_object.fetch("share_count", {}) if story_node_object["comet_sections"]["content"]["story"]["comet_sections"].key? "message" text = story_node_object["comet_sections"]["content"]["story"]["comet_sections"]["message"]["story"]["message"]["text"] else text = "" end feedback_object["comment_list_renderer"]["feedback"]["comment_count"]["total_count"] num_comments = feedback_object.has_key?("comment_list_renderer") ? feedback_object["comment_list_renderer"]["feedback"]["comment_count"]["total_count"] : feedback_object["comment_count"]["total_count"] post_details = { id: video_object["id"], num_comments: num_comments, num_shares: share_count_object.fetch("count", nil), num_views: feedback_object["comet_ufi_summary_and_actions_renderer"]["feedback"]["video_view_count"], reshare_warning: feedback_object["comet_ufi_summary_and_actions_renderer"]["feedback"]["should_show_reshare_warning"], video_preview_image_url: video_object["preferred_thumbnail"]["image"]["uri"], video_url: video_object["playable_url_quality_hd"] || video_object["playable_url"], text: text, created_at: creation_date, profile_link: story_node_object["comet_sections"]["context_layout"]["story"]["comet_sections"]["actor_photo"]["story"]["actors"][0]["url"], has_video: true } post_details[:video_preview_image_file] = Forki.retrieve_media(post_details[:video_preview_image_url]) post_details[:video_file] = Forki.retrieve_media(post_details[:video_url]) post_details[:reactions] = reaction_counts post_details end |
#extract_video_post_data_alternative(graphql_object_array) ⇒ Object
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/forki/scrapers/post_scraper.rb', line 194 def extract_video_post_data_alternative(graphql_object_array) sidepane_object = graphql_object_array.find { |graphql_object| graphql_object.key?("tahoe_sidepane_renderer") } video_object = graphql_object_array.find { |graphql_object| graphql_object.keys == ["video"] } feedback_object = sidepane_object["tahoe_sidepane_renderer"]["video"]["feedback"] reaction_counts = extract_reaction_counts(sidepane_object["tahoe_sidepane_renderer"]["video"]["feedback"]["cannot_see_top_custom_reactions"]["top_reactions"]) share_count_object = feedback_object.fetch("share_count", {}) post_details = { id: video_object["id"], num_comments: feedback_object["comments_count_summary_renderer"]["feedback"]["total_comment_count"], num_shares: share_count_object.fetch("count", nil), num_views: feedback_object["video_view_count"], reshare_warning: feedback_object["should_show_reshare_warning"], video_preview_image_url: video_object["video"]["preferred_thumbnail"]["image"]["uri"], video_url: video_object["video"]["playable_url_quality_hd"] || video_object["video"]["playable_url"], text: sidepane_object["tahoe_sidepane_renderer"]["video"]["creation_story"]["comet_sections"]["message"]["story"]["message"]["text"], created_at: video_object["video"]["publish_time"], profile_link: sidepane_object["tahoe_sidepane_renderer"]["video"]["creation_story"]["comet_sections"]["actor_photo"]["story"]["actors"][0]["url"], has_video: true } post_details[:video_preview_image_file] = Forki.retrieve_media(post_details[:video_preview_image_url]) post_details[:video_file] = Forki.retrieve_media(post_details[:video_url]) post_details[:reactions] = reaction_counts post_details end |
#extract_video_post_data_from_watch_page(graphql_strings) ⇒ Object
Extract data from a non-live video post on the watch page
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
# File 'lib/forki/scrapers/post_scraper.rb', line 250 def extract_video_post_data_from_watch_page(graphql_strings) return extract_live_video_post_data_from_watch_page(graphql_strings) if current_url.include?("live") video_object = graphql_strings.map { |g| JSON.parse(g) }.find { |x| x.key?("video") } creation_story_object = JSON.parse(graphql_strings.find { |graphql_string| (graphql_string.include?("creation_story")) && \ (graphql_string.include?("live_status")) }) video_permalink = creation_story_object["creation_story"]["shareable"]["url"].delete("\\") media_object = video_object["video"]["story"]["attachments"][0]["media"] reaction_counts = extract_reaction_counts(creation_story_object["feedback"]["cannot_see_top_custom_reactions"]["top_reactions"]) post_details = { id: video_object["id"], num_comments: creation_story_object["feedback"]["total_comment_count"], num_shares: nil, # Not present for watch feed videos? num_views: creation_story_object["feedback"]["video_view_count_renderer"]["feedback"]["video_view_count"], reshare_warning: creation_story_object["feedback"]["should_show_reshare_warning"], video_preview_image_url: video_object["video"]["story"]["attachments"][0]["media"]["preferred_thumbnail"]["image"]["uri"], video_url: (media_object.fetch("playable_url_quality_hd", nil) || media_object.fetch("playable_url", nil)).delete("\\"), text: (creation_story_object["creation_story"]["message"] || {})["text"], created_at: video_object["video"]["story"]["attachments"][0]["media"]["publish_time"], profile_link: video_permalink[..video_permalink.index("/videos")], has_video: true } post_details[:video_preview_image_file] = Forki.retrieve_media(post_details[:video_preview_image_url]) post_details[:video_file] = Forki.retrieve_media(post_details[:video_url]) post_details[:reactions] = reaction_counts post_details end |
#find_number_of_views ⇒ Object
Searches the DOM to finds the number of times a (video) post has been viewed. Returns nil if it can’t find a DOM element with the view count
13 14 15 16 17 18 |
# File 'lib/forki/scrapers/post_scraper.rb', line 13 def find_number_of_views views_pattern = /[0-9MK, ]+Views/ spans = all("span") views_span = spans.find { |s| s.text(:all) =~ views_pattern } extract_int_from_num_element(views_span) end |
#get_graphql_objects(graphql_strings) ⇒ Object
43 44 45 |
# File 'lib/forki/scrapers/post_scraper.rb', line 43 def get_graphql_objects(graphql_strings) graphql_strings.map { |graphql_object| JSON.parse(graphql_object) } end |
#is_post_available? ⇒ Boolean
87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/forki/scrapers/post_scraper.rb', line 87 def is_post_available? begin # This Video Isn't Available Anymore find("span", wait: 5, text: "content isn't available", exact_text: false) rescue Capybara::ElementNotFound, Selenium::WebDriver::Error::StaleElementReferenceError begin find("span", wait: 5, text: "This Video Isn't Available Anymore", exact_text: false) rescue Capybara::ElementNotFound, Selenium::WebDriver::Error::StaleElementReferenceError return true end end false end |
#parse(url) ⇒ Object
Uses GraphQL data and DOM elements to collect information about the current post
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
# File 'lib/forki/scrapers/post_scraper.rb', line 330 def parse(url) validate_and_load_page(url) graphql_strings = find_graphql_data_strings(page.html) post_data = extract_post_data(graphql_strings) post_data[:url] = url user_url = post_data[:profile_link] 5.times do begin post_data[:screenshot_file] = take_screenshot break rescue Net::ReadTimeout; end sleep(5) end # page.quit # Close browser between page navigations to prevent cache folder access issues post_data[:user] = User.lookup(user_url).first page.quit post_data rescue Net::ReadTimeout # Eat it? rescue StandardError => e raise e ensure page.quit end |
#take_screenshot ⇒ Object
318 319 320 321 322 323 324 325 326 327 |
# File 'lib/forki/scrapers/post_scraper.rb', line 318 def take_screenshot # First check whether post being scraped has a fact check overlay. If it does clear it. begin find('div[aria-label=" See Photo "]').click() || find('div[aria-label=" See Video "]').click() rescue Capybara::ElementNotFound # Do nothing if element not found end save_screenshot("#{Forki.temp_storage_location}/facebook_screenshot_#{SecureRandom.uuid}.png") end |