Skip to content

Getting the likes and comments of a photo from Facebook using Selenium

I’m looking forward to getting what the title describes. I’ve already found the way to log in and get the photos of any profile that I search for. But when it comes to the comments or likes of any photo that I select, I cannot get them. By this, I mean that Chromedriver clicks on the photo for displaying it, and I would like, while the photo is displayed, to get just the number of likes (just the ones in blue) and the comments that are posted on that photo (right panel). I’m not finding any tutorial or post that helps (indeed I’ve searched a lot).

Here’s the way I’m looking for the photos, in case you need to see some of the code:

imagenes = []
for i in ['photos_of','photos_all']:
    driver.get("https:/" + i + "/")
    n_scrolls = 3
    for j in range(1, n_scrolls):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        anchors = driver.find_elements_by_tag_name('a')
        anchors = [a.get_attribute('href') for a in anchors]
        anchors = [a for a in anchors if str(a).startswith("")]
        for a in anchors:
            imagen = driver.find_elements_by_tag_name("img")

Thanks in advance and pardon for my English.



The XPath to locate amount of likes under a photo in a photo viewer view is

//div[@aria-label="Photo Viewer"]//span[@class='pcp91wgn']

or in CSS selector syntax:

div[aria-label="Photo Viewer"] span[class="pcp91wgn"]

The comments there can be located with this CSS Selector

div[aria-label="Photo Viewer"] div[class="ecm0bbzt e5nlhep0 a8c37x1j"]

or with XPath syntax:

//div[@aria-label="Photo Viewer"]//div[@class="ecm0bbzt e5nlhep0 a8c37x1j"]

So you can iterate the list of links like this:

from import By
from import WebDriverWait
from import expected_conditions as EC

photoview_comment_xpath = '//div[@aria-label="Photo Viewer"]//div[@class="ecm0bbzt e5nlhep0 a8c37x1j"]'
photoview_likes_amount_css = 'div[aria-label="Photo Viewer"] span[class="pcp91wgn"]'

likes = []
comments = []
for link in links:
    like = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, photoview_likes_amount_css))).text.strip()
    comments_elements = driver.find_elements_by_xpath(photoview_comment_xpath)
    for comment in comments_elements:

I don’t think you will find tutorial about each specific web site. What you have to learn here is how to find stable unique locators for the web elements, and XPath and css selectors syntax