【问题标题】:Scraping Facebook Messages from html files with rvest使用 rvest 从 html 文件中抓取 Facebook 消息
【发布时间】:2018-04-19 22:15:54
【问题描述】:

因为可以下载您的 Facebook 数据存档的副本,它提供了您拥有的每个单独聊天的 html 文件。我希望能够将其放入数据框中以进行进一步分析。

其中一个文件的示例如下所示:

我已经在此处上传了该 html 文件的示例:https://gist.githubusercontent.com/eldenvo/182efcd870f74d715b202f3ccdae335e/raw/1b53610459790489efb43ab6caa0f15103d391a1/facebook-message.html

我的理想是将数据放入包含以下列的数据框中:发件人、消息、时间。

所以使用

library(rvest)

doc <- "https://gist.githubusercontent.com/eldenvo/182efcd870f74d715b202f3ccdae335e/raw/1b53610459790489efb43ab6caa0f15103d391a1/facebook-message.html"
doc %>% read_html()

返回

#> {xml_document}
#> <html>
#> [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n<base href="../">\n<style type="text/c ...
#> [2] <body>\n<a href="html/messages.htm">Back</a><br><br><div class="thread">Conversation with p1, p2<div class="message ..

并使用 Chrome 中的选择器工具尝试提取更多内容:

doc %>% read_html() %>% html_node(xpath = '/html/body/div/div[1]')
#> {xml_node}
#> <div class="message">
#> [1] <div class="message_header">\n<span class="user">p1</span><span class="meta">Monday, 19 March 2012 at 23:29 UTC</sp ...

doc %>% read_html() %>% html_node(xpath = '/html/body/div/p/text()') %>% html_text()

#> [1] "I didn't see your message before, i'm sorry that i didn't answer. Next time i promise !!"

我对@9​​87654327@ 或rvest 不是很熟悉,所以我不确定将完整的消息列表和相关信息提取到data.frame 中的最佳方法。

【问题讨论】:

    标签: html r web-scraping rvest


    【解决方案1】:

    这篇文章可以帮到你很多:https://blog.rstudio.com/2014/11/24/rvest-easy-web-scraping-with-r/

    尤其是http://selectorgadget.com 的提示,它可以更轻松地找到要提取的合适标签。

    您当前的示例将像这样工作:

    library(tidyverse)
    library(rvest)
    
    doc <-  "https://gist.githubusercontent.com/eldenvo/182efcd870f74d715b202f3ccdae335e/raw/1b53610459790489efb43ab6caa0f15103d391a1/facebook-message.html"
    
    pg <- doc %>% read_html()
    

    我们创建了一个小助手,可以重复使用几次:

    extract_nodes <- function(pg, css) {
      pg %>%
        html_nodes(css) %>%
        html_text()
    }
    

    接下来,我们提取有关日期的相关部分。之后,我们需要处理和解析日期。我删除了字符串“Monday, ....”的开头,之后只需为parse_datetime 设置正确的参数,可以在帮助文件中找到。

    dates <- pg %>%
      extract_nodes("span[class='meta']") %>%
      str_replace("^.*,\\s", "") %>%
      parse_datetime(format = "%d %B %Y %* %H:%M %*")
    

    一旦确定日期,我们就可以轻松解析消息和用户:

    result <- data_frame(
      user = extract_nodes(pg, "span[class='user']"),
      dates = dates,
      message = extract_nodes(pg, "p")
    
    )
    result
    #> # A tibble: 4 x 3
    #>    user               dates
    #>   <chr>              <dttm>
    #> 1    p1 2012-03-19 23:29:00
    #> 2    p2 2012-03-19 15:39:00
    #> 3    p1 2012-03-19 08:34:00
    #> 4    p1 2012-03-18 20:24:00
    #> # ... with 1 more variables: message <chr>
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2023-03-21
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多