【发布时间】:2019-03-19 14:45:00
【问题描述】:
我正在尝试从包含表格和链接的网络中抓取数据。我可以成功下载带有链接文本“分数”的表格。但是,我想捕获完整的href URL,而不是缩短的 URL。
但是,我想我的 URL 缩短为 rvest。我不知道如何获得完整的“url”,我可以如下循环以获取所需的数据,然后将所有内容转换为数据框。
library(rvest)
# Load the page
odi_score_url <- read_html('http://stats.espncricinfo.com/ci/engine/records/team/match_results.html?class=2;id=2019;type=year')
urls <- odi_score_url %>%
html_nodes('td:nth-child(7) .data-link') %>%
html_attr("href")
links <- odi_score_url %>%
html_nodes('td:nth-child(7) .data-link') %>%
html_text()
# Combine `links` and `urls` into a data.frame
score_df <- data.frame(links = links, urls = urls, stringsAsFactors = FALSE)
head(score_df)
links urls
1 ODI # 4074 /ci/engine/match/1153840.html
2 ODI # 4075 /ci/engine/match/1153841.html
3 ODI # 4076 /ci/engine/match/1153842.html
4 ODI # 4077 /ci/engine/match/1144997.html
5 ODI # 4078 /ci/engine/match/1144998.html
6 ODI # 4079 /ci/engine/match/1144999.html
遍历score_df中的每一行并获取所需数据
for(i in score_df) {
text <- read_html(score_df$urls[i]) %>% # load the page
html_nodes(".match-detail--item:nth-child(3) span , .match-detail--item:nth-child(3) h4 ,
.stadium-details+ .match-detail--item span , .stadium-details ,
.stadium-details+ .match-detail--item h4 , .cscore_score , .cscore_name--long") %>% # isloate the text
html_text() # get the text
## Create the dataframe
}
感谢您的帮助!!!
提前致谢
【问题讨论】:
-
您可以通过将第一部分粘贴到抓取的部分来构建长 URL:
score_df <- data.frame(links = links, urls = paste0("http://stats.espncricinfo.com", urls), stringsAsFactors = FALSE)
标签: r web-scraping rvest