【问题标题】:R Web scraping from different URLsR 从不同的 URL 抓取网页
【发布时间】:2018-01-16 15:09:20
【问题描述】:

我正在网页上抓取页面

http://catalog.ihsn.org/index.php/catalog#_r=&collection=&country=&dtype=&from=1890&page=1&ps=100&sid=&sk=&sort_by=nation&sort_order=&to=2017&topic=&view=s&vk=

从这个网址,我通过以下代码建立了一个数据框:

dflist <- map(.x = 1:417, .f = function(x) {
 Sys.sleep(5)
 url <- ("http://catalog.ihsn.org/index.php/catalog#_r=&collection=&country=&dtype=&from=1890&page=1&ps=100&sid=&sk=&sort_by=nation&sort_order=&to=2017&topic=&view=s&vk=")
read_html(url) %>%
html_nodes(".title a") %>%
html_text() %>%
as.data.frame()
}) %>% do.call(rbind, .)

为了获取我感兴趣的所有数据,我重复了相同的代码,它似乎工作得很好,尽管由于 Sys.sleep() 的原因当然有点慢。

一旦我尝试抓取应包含在数据框中的单个项目描述,我的问题就出现了。

例如,第一个项目描述在

http://catalog.ihsn.org/index.php/catalog/7118/study-description

第二个项目描述在

http://catalog.ihsn.org/index.php/catalog/6606/study-description

等等。

我的问题是我找不到动态方法来抓取所有项目的页面并将它们插入数据框中,因为 URL 中的数字不是渐进式的,也不是链接末尾的。

为了让事情更清楚,这是我正在抓取的网站的结构:

1.http://catalog.ihsn.org/index.php/catalog#_r=&collection=&country=&dtype=&from=1890&page=1&ps=100&sid=&sk=&sort_by=nation&sort_order=&to=2017&topic=&view=s&vk=
   1.1.   http://catalog.ihsn.org/index.php/catalog/7118
        1.1.a http://catalog.ihsn.org/index.php/catalog/7118/related_materials
        1.1.b http://catalog.ihsn.org/index.php/catalog/7118/study-description
        1.1.c. http://catalog.ihsn.org/index.php/catalog/7118/data_dictionary

我已经成功爬到 1 级。但不能达到 1.1.b 级。 (study-description) 是我感兴趣的,因为 URL 的动态元素(在本例中为:7118)在该级别网站的 6000 多个页面中并不一致。

【问题讨论】:

  • 目前还不清楚您的问题是什么。如果您在尝试抓取描述时清楚地包括您的问题,这将有助于我们为您提供帮助。
  • 我的问题是我找不到动态方法来抓取所有项目的页面并将它们插入数据框中,因为 URL 中的数字不是渐进式的,也不是链接末尾的。
  • 您可以使用html_attr("href") 代替html_text 获取各个网址,然后使用purrr 来遍历该列表。
  • 谢谢,这可能是一个想法,但是您指的是哪个命令purrr 命令?
  • 您可以只使用mapapply 系列函数并创建一个辅助函数来遍历网址

标签: r dataframe web-scraping


【解决方案1】:

您必须从 .title a 中提取更深层次的 url,然后将它们也刮掉。这是一个关于如何使用rvesttidyverse 的小示例

library(tidyverse)
library(rvest)

scraper <- function(x) {

  Sys.sleep(5)
  url <- sprintf("http://catalog.ihsn.org/index.php/catalog#_r=&collection=&country=&dtype=&from=1890&page=%s&ps=100&sid=&sk=&sort_by=nation&sort_order=&to=2017&topic=&view=s&vk=", x)

  html <- read_html(url)

  tibble(title = html_nodes(html, ".title a") %>% html_text(trim = TRUE),
         project_url = html_nodes(html, ".title a") %>% html_attr("href")) 
}

result <- map_df(1:2, scraper) %>% 
  mutate(study_description = map(project_url, ~read_html(sprintf("%s/study-description", .x)) %>% html_node(".xsl-block") %>% html_text()))

对于您想要做的所有事情,这并不完整,但应该向您展示一种方法。

【讨论】:

  • 谢谢,这很有用。我没有意识到~read_html 命令。
  • ~read_html 不是命令,它是用于迭代列表或向量的函数的公式表示。您应该搜索并阅读有关 purrr 包的更多信息,该包在此示例中进行迭代。
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 2021-07-17
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多