R删除字符串中通配符周围的字符
R remove characters surrounding wildcard in string
我有一个向量,列出了在包含 URL 的网站中找到的各种类型的 HTML,其特征是通配符:([^<]* )。到目前为止,我已经能够将链接拉入我需要的数据框中,但无法清理它们以便可以访问它们。
如何在不影响 URL 的情况下删除所有标签?
# Vector of HTML tags surrounding URL
x <- c('\t\t\t<div><a href=\"([^<]*)\">([^<]*)</a></div>','\t\t</tr><tr><td><a href=\"([^<]*)\">([^<]*)</a></td>','\t\t\t<td><a href=\"([^<]*)\">([^<]*)</a></td>')
输入:
URL <- "https://www.atf.gov/resource-center/data-statistics"
html <- paste(readLines(URL))
输出:
Link
Title
"https://www.atf.gov/file/144871/download"
Canada 2014-2019
"https://www.atf.gov/node/79436"
2019
我目前正在使用的代码:
dlall <- list()
for(i in x){
datalines <- grep(i,html,value=TRUE)
dl_all <- rbind(data.frame(datalines), data.frame(dl_all))
}
类似于 Wiktor Stribiżew 使用 R >= 4.1:
library(rvest)
url <- "https://www.atf.gov/resource-center/data-statistics"
df <- read_html(url) |> html_nodes("a") |>
{\(x) data.frame(
Link = x |> html_attr("href"),
Title = x |> html_text())
}()
给予:
tail(df)
Link Title
203 https://www.justice.gov/jmd/eeo-program-status-report No Fear Act
204 https://oig.justice.gov/hotline/whistleblower-protection Whistleblower Rights & Protections
205 https://www.atf.gov/home/site-map Site Map
206 https://www.atf.gov/resource-center/accessibility-policy Accessibility & Plug-Ins
207 https://www.atf.gov/<front> ATF.gov
208 https://www.justice.gov U.S. Department of Justice
我有一个向量,列出了在包含 URL 的网站中找到的各种类型的 HTML,其特征是通配符:([^<]* )。到目前为止,我已经能够将链接拉入我需要的数据框中,但无法清理它们以便可以访问它们。
如何在不影响 URL 的情况下删除所有标签?
# Vector of HTML tags surrounding URL
x <- c('\t\t\t<div><a href=\"([^<]*)\">([^<]*)</a></div>','\t\t</tr><tr><td><a href=\"([^<]*)\">([^<]*)</a></td>','\t\t\t<td><a href=\"([^<]*)\">([^<]*)</a></td>')
输入:
URL <- "https://www.atf.gov/resource-center/data-statistics"
html <- paste(readLines(URL))
输出:
Link | Title |
---|---|
"https://www.atf.gov/file/144871/download" | Canada 2014-2019 |
"https://www.atf.gov/node/79436" | 2019 |
我目前正在使用的代码:
dlall <- list()
for(i in x){
datalines <- grep(i,html,value=TRUE)
dl_all <- rbind(data.frame(datalines), data.frame(dl_all))
}
类似于 Wiktor Stribiżew 使用 R >= 4.1:
library(rvest)
url <- "https://www.atf.gov/resource-center/data-statistics"
df <- read_html(url) |> html_nodes("a") |>
{\(x) data.frame(
Link = x |> html_attr("href"),
Title = x |> html_text())
}()
给予:
tail(df)
Link Title
203 https://www.justice.gov/jmd/eeo-program-status-report No Fear Act
204 https://oig.justice.gov/hotline/whistleblower-protection Whistleblower Rights & Protections
205 https://www.atf.gov/home/site-map Site Map
206 https://www.atf.gov/resource-center/accessibility-policy Accessibility & Plug-Ins
207 https://www.atf.gov/<front> ATF.gov
208 https://www.justice.gov U.S. Department of Justice