我目前正在做一個專案,從一個網站的源代碼上刮取資訊。這是我得到的代碼:
require(dplyr)
require(tidyverse)
require(stringi)
require(stringr)
require(rvest)
require(purrr)
library(data.table)
datalist = list()
# Looping through all pages on the website
for (page in 1。 91){
# 構建下載html源代碼的URL。
WebUrl <- paste0("https://www.apple.com/newsroom/archive/?page=",
page)
download.file(WebUrl,)
destfile = paste0("tempdir/Source code"。 頁面, ". txt"))
# 從源代碼中抓取相關節點并將其轉換為df。
webpages_df <- webpages %>%。
html_nodes("a") %>%
map(html_attrs) %>%
map_df(~as.list(.))
# 從 "aria-label "列中洗掉NA值,其中相關的字串是和。
# 重命名該列
頭條新聞 <- as.data.frame(webpages_df$`aria-label`) %> %
filter(! is. na(webpages_df$`aria-label`) %>%
setnames(old = "webpages_df$`aria-label`"。 new = "Strings")
# 移除不相關的字串
# Regex對任何后面有數字、逗號和四位數的詞進行匹配。例如:
# September 1, 2021
頭條新聞 <- 頭條新聞 %>%
filter(grepl("([A-Z]w s[0-9][0-9]? , s[0-9][0-9][0-9]?)",字串))
# 在行上回圈,提取不同的變數并存盤起來。
# 每個變數都用regex創建,以提取相關資訊。
# 回圈的目標是從源檔案中提取給定的值。
# 節點的相關資訊。
for (r in 1 : nrow(headlines)){
日期 < - stri_extract_all(headlines$Strings, regex= "([A-Z]w s[0-9][0-9]? , s[0- 9][0-9][0-9][0-9]?)")
類別 < - stri_extract_all(headlines$Strings, regex = "([A-Z][A-Z][A-Z][A-Z][A-Z]sw |[A-Z][A-Z]/w )"/span>)
標題 < - str_remove_all(headlines$Strings, 模式= "([A-Z]w s[0-9][0-9]? , s[0-9][0-9][0-9][0-9]) (-s[A-Z]?w .[A-Z] ..)" )
article.url <- webpages_df %>%
filter(grepl( pattern = "(/[a-z]? w[0-9] /[0-9] /[a-z]?w .w [a-z]?)", href=))
article.url <- paste0(/span>"https://www.apple. com", article.url$href)
tempmatrix < -矩陣(c(dates。 類別,標題,文章。 url), ncol = 4)
datalist[[r] < - rbind(tempmatrix, datalist)
}
}
這樣做可以將所有頁面上的各種源代碼下載到設定的目錄中。但我似乎無法讓嵌套回圈發揮作用。我的目標是回圈瀏覽每個源代碼檔案,并創建日期、類別、標題和URL等變數,然后將其追加到回圈外的一個串列中。然后將其轉換為具有上述列的結構化資料框架。
雖然這個代碼塊不作業,但我可以讓它在沒有嵌套回圈和tempmatrix/datalist[[r]]的情況下作業。這樣做的結果是只有我想要的結構中的最后一個檔案資訊。
非常感謝關于如何解決我手頭問題的意見/建議。我是一個R的新手,所以我的代碼可能是低效的。
uj5u.com熱心網友回復:
嘗試在你的內回圈中迭代建立一個 data.frame,然后在你的外回圈的每次迭代中將該資料框架追加到一個串列中。如果這不起作用,請告訴我。
for (page in 1: 91){
中間的<- c(/span>)
...
for (r in 1。 nrow(headlines)){
...
中間的<- rbind(tempmatrix, 中間的)
}
datalist[[page]] <- intermediate
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322203.html
標籤:
上一篇:基于字串串列的公式輸出
