html - R删除字符串中通配符周围的字符
问题描述
我有一个向量列出了在包含 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))
输出:
关联 | 标题 |
---|---|
“https://www.atf.gov/file/144871/download” | 加拿大 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))
}
解决方案
与使用 R >= 4.1的Wiktor Stribiżew类似:
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
推荐阅读
- angular - 如何将锚标记添加到 ngx-datatable-column
- reactjs - 应用程序创建 w create-react-app-ts 缺少引导 css
- javascript - Webassembly 最终会在浏览器中呈现为 HTML 吗?
- python - 使用 numpy 对特定范围内的数组值求和
- asp.net - Asp.net WebAPI - 强制使用 HTTPS?
- repository - bitbucket 在一台计算机上,但在另一台计算机上还可以
- c# - 有条件地加入 2 个列表的子列表
- c# - Web 发布找不到 Microsoft.Build.Framework
- sql - max(field2) 中的 max(field1) 必须使用内部连接吗?
- java - 停止嵌入式 Tomcat 时应用程序挂起