【问题标题】:Parse public facebook posts with beautifulsoup / python用 beautifulsoup / python 解析公开的 facebook 帖子
【发布时间】:2016-11-05 17:46:20
【问题描述】:

我尝试解析针对特定主题(如公司或产品)发布的 Facebook 帖子。作为示例帖子来自这里https://www.facebook.com/search/latest/?q=facebook

我可以正确登录 facebook(使用 python),并且我还可以获取包含我正在寻找的帖子的页面的源代码。经过一些手动代码审查后,我发现我想获得以下信息:

<div class="_5pbx userContent" data-ft="&#123;&quot;tn&quot;:&quot;K&quot;&#125;">
    <p>Here is the text of the post I need
    </p>
</div>

所以我从 beautifulsoup 和以下代码开始:

soup = BeautifulSoup(pageSourceCode.content, 'html.parser')

for msg in soup.find_all('div'):
    print (msg.get('class')

结果我只得到了这个......

[u'hidden_elem']

有人有抓取 Facebook 帖子的经验吗?我只需要这个用于我自己和教育目的

【问题讨论】:

  • 此外,为了测试目的,我尝试执行以下操作“print soup.find_all('p')”,它只打印以下结果“[]”

标签: python facebook web-scraping beautifulsoup


【解决方案1】:

以下代码应该可以工作

soup = BeautifulSoup(pageSourceCode.content, 'html.parser')

divs = soup.find_all('div', class_="_5pbx userContent")
for div in divs:
    p = div.find('p')
    print(p.get_text())

【讨论】:

  • 感谢您的回复,我尝试了您的代码,但它不起作用:( ...所以我玩了一下,发现了一些东西...如果我打印出“divs”它是空的“[]”,如果我打印它的类型,它会打印出“”,这在我看来不错?如果我改变了 soup.find_all('div', class_="_5pbx userContent ") to soup.find_all('div') 我得到了相同的类型,并且用“print divs”打印了很多东西如果嵌套了 class_="_5pbx userContent" div 会不会有问题?因为它喜欢在代码中排在第 5 位 (
    )
  • 不,div嵌套是没有问题的。只要确保类和源代码中的完全一样。
【解决方案2】:

问题是,我搜索的课程写在评论中。所以我必须首先在评论上搜索 div,对其进行编码,然后创建一个新的汤对象。之后就可以通过 css 选择器选择我正在搜索的 div。

comment = soup.select('code#u_0_11')
comment_data = comment[0].string.encode("utf-8")
soup = BeautifulSoup(comment_data, 'html.parser')
divs = soup.select('div._5pbx.userContent')

现在我可以通过以下方式打印它:

for div in divs:
    p = div.find_all('p')
    print (p[0].text.encode('utf-8')

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签