【问题标题】:Error with rvest packagervest 包出错
【发布时间】:2017-09-03 08:19:19
【问题描述】:

我正在尝试从证券集体诉讼文件网站上跨多个页面 (233) 抓取表格。我的代码如下:

install.packages("rvest")
install.packages("magrittr")
install.packages("xml2")

library(xml2)
library(rvest)
library(magrittr)
library(data.table)


i <- 1:233
urls <- paste0("http://securities.stanford.edu/filings.html?page=", i)

get_table <- function(url) {
  url %>%
    read_html() %>%
    html_nodes(xpath = '//*[@id="records"]/table') %>%
    html_table()
}

results <- sapply(urls, get_table)

代码导致如下错误:

xpath_element() 中的错误:
找不到函数“xpath_element”

有什么想法吗?

我尝试重新启动 R,重新启动计算机并更新所有软件包。

【问题讨论】:

  • install.packages("selectr") 为我解决了这个问题。

标签: r web-scraping rvest


【解决方案1】:

我认为这段代码会让你接近你所需要的。

suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(rvest))


# iterate over the first 10 pages
iter_page <- 1:10
pb <- progress_estimated(length(iter_page))

# define function to scrape the table data from a page
get_table <- function(i) {
  base_url <- "http://securities.stanford.edu/filings.html?page="
  url <-  paste0(base_url, i)
  url %>%
    read_html() %>%
    html_nodes(xpath = '//*[@id="records"]/table') %>%
    html_table() %>% 
    .[[1]] %>%
    as_tibble()
}  

# scrape first 10 pages
map_df(iter_page, ~ {
  pb$tick()$print()
  df <- get_table(.x)
  Sys.sleep(sample(10, 1) * 0.1)
  df
})
#> # A tibble: 200 x 5
#>                                                       `Filing Name`
#>                                                               <chr>
#>  1                                    Dr. Reddy's Laboratories Ltd.
#>  2                                             PetMed Express, Inc.
#>  3                                                   Top Ships Inc.
#>  4                                                     Sevcon, Inc.
#>  5                                                     XCerra Corp.
#>  6                                               Zillow Group, Inc.
#>  7                                                   ShoreTel, Inc.
#>  8 Teva Pharmaceutical Industries Ltd. : American Depository Shares
#>  9                                                    Depomed, Inc.
#> 10                                        Blue Apron Holdings, Inc.
#> # ... with 190 more rows, and 4 more variables: `Filing Date` <chr>,
#> #   `District Court` <chr>, Exchange <chr>, Ticker <chr>

【讨论】:

  • 谢谢。我运行了代码,但仍然收到相同的错误消息。运行 map_df(.) 后,R 开始抓取 (|====== | 10% ~1 m remaining),但不久后结束并显示错误消息 Error in xpath_element(&lt;S4 object of class "Element"&gt;) : could not find function "xpath_element"
【解决方案2】:

重新安装了 R - 这次不是通过 Anaconda - 现在代码可以工作了。很抱歉浪费了你们的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2015-09-09
    • 2018-12-01
    • 2019-11-14
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多