使用 Selenium 从 Facebook 获取照片的点赞和评论

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

我期待看到标题所描述的内容。我已经找到了登录并获取我搜索的任何个人资料照片的方法。 但是当涉及到我select的任何照片的评论或喜欢时,我无法获得它们。 通过这个,我的意思是 Chromedriver 单击照片以显示它,我想在显示照片时只获得喜欢的数量(只有蓝色的)和 post 的评论在那张照片上编辑(右面板)。 我没有找到任何有帮助的教程或 post(实际上我已经搜索了很多)。

这是我查找照片的方式,以防您需要查看一些代码:

time.sleep(4)
imagenes = []
for i in ['photos_of','photos_all']:
    driver.get("https:/www.facebook.com/userBasedOnURL/" + i + "/")
    time.sleep(3)
    n_scrolls = 3
    for j in range(1, n_scrolls):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(3)
        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("https://www.facebook.com/photo")]
        #print(anchors)
        for a in anchors:
            driver.get(a)
            time.sleep(3)
            imagen = driver.find_elements_by_tag_name("img")
            #print(imagen)
            imagenes.append(imagen[0].get_attribute("src"))
imagenes

提前致谢,请原谅我的英语。

在照片查看器视图中定位照片下点赞数量的 XPath 是

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

或 CSS 选择器语法:

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

可以使用此 CSS 选择器

找到那里的评论
div[aria-label="Photo Viewer"] div[class="ecm0bbzt e5nlhep0 a8c37x1j"]

或使用 XPath 语法:

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

因此您可以像这样迭代链接列表:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support 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:
    driver.get(link)
    like = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, photoview_likes_amount_css))).text.strip()
    like.append(like)
    comments_elements = driver.find_elements_by_xpath(photoview_comment_xpath)
    for comment in comments_elements:
        comments.append(comment.text.strip())

我认为您不会找到关于每个特定网站的教程。您在这里必须学习的是如何为 Web 元素找到稳定的唯一定位器,以及 XPath 和 css 选择器语法