使用 rvest 从多个 XML 文件创建数据库

Using rvest to creating a database from multiple XML files

使用 R 从多个在线 XML 文件中提取相关数据以创建数据库

刚开始学R做文本分析。这是我正在尝试做的事情:我正在尝试在 r 中使用 rvest 从在线 XML 文件中创建第 116 届国会法案摘要的 CSV 数据库。数据库应该有两列:

  1. 账单标题。
  2. 法案的摘要文本。

网站来源为https://www.govinfo.gov/bulkdata/BILLSUM/116/hr

我遇到的问题是

我想收集搜索返回的所有演讲。所以我需要在网上抓取多个链接。但我不知道如何确保 r 运行具有一系列不同链接的功能,然后提取预期的数据。

我尝试了以下代码,但我不确定如何将它们准确地应用到我的具体问题中。另外,我收到了我的代码的错误报告。请在下面查看我的代码。提前感谢您的帮助!

library(rvest)    
library(tidyverse)
library(purrr)
html_source <- "https://www.govinfo.gov/bulkdata/BILLSUM/116/hr?page="


map_df(1:997, function(i) {  

  cat(".")

  pg <- read_html(sprintf(html_source, i))

  data.frame(title = html_text(html_nodes(pg, "title")),
             bill_text %>% html_node("summary-text") %>% html_text(),
             stringsAsFactors = FALSE) 

}) -> Bills 

open.connection(x, "rb") 中的错误:HTTP 错误 406。

该页面的底部是一个 link 到一个包含所有 XML 文件的 zip 文件,因此与其单独抓取每个文件(这将变得繁琐 a suggested crawl-delay of 10s ) 你可以只下载 zipfile 并用 xml2 解析 XML 文件(rvest 用于 HTML):

library(xml2)
library(purrr)

local_dir <- "~/Downloads/BILLSUM-116-hr"
local_zip <- paste0(local_dir, '.zip')

download.file("https://www.govinfo.gov/bulkdata/BILLSUM/116/hr/BILLSUM-116-hr.zip", local_zip)
# returns vector of paths to unzipped files
xml_files <- unzip(local_zip, exdir = local_dir)

bills <- xml_files %>%
    map(read_xml) %>% 
    map_dfr(~list(
        # note xml2 functions only take XPath selectors, not CSS ones
        title = xml_find_first(.x, '//title') %>% xml_text(),
        summary = xml_find_first(.x, '//summary-text') %>% xml_text()
    ))

bills
#> # A tibble: 1,367 x 2
#>    title                               summary                             
#>    <chr>                               <chr>                               
#>  1 For the relief of certain aliens w… Provides for the relief of certain …
#>  2 "To designate the facility of the … "Designates the facility of the Uni…
#>  3 Consolidated Appropriations Act, 2… <p><b>Consolidated Appropriations A…
#>  4 Financial Institution Customer Pro… <p><strong>Financial Institution Cu…
#>  5 Zero-Baseline Budget Act of 2019    <p><b>Zero-Baseline Budget Act of 2…
#>  6 Agriculture, Rural Development, Fo… "<p><b>Highlights: </b></p> <p>This…
#>  7 SAFETI Act                          <p><strong>Security for the Adminis…
#>  8 Buy a Brick, Build the Wall Act of… <p><b>Buy a Brick, Build the Wall A…
#>  9 Inspector General Access Act of 20… <p><strong>Inspector General Access…
#> 10 Federal CIO Authorization Act of 2… <p><b>Federal CIO Authorization Act…
#> # … with 1,357 more rows

summary 列是 HTML 格式的,但总的来说这已经很干净了。