r - 如何通过 R 抓取超链接并在输出文件中保持超链接可点击?
问题描述
我是一名 R 初学者,正在尝试查看 StackOverflow 中所有前 500/1000 个投票/常见问题。
我需要一个带有两个变量的data.frame,分别包含问题和这个问题的超链接。
网页在这里,需要这样的超链接:
<h3><a href="/questions/5963269/how-to-make-a-great-r-reproducible-example" class="question-hyperlink">How to make a great R reproducible example</a></h3>
输出如下:
question link
1 how-to-make-a-great-r-reproducible-example <questions/5963269/how-to-make-a-great-r-reproducible-example>
2 ...
3 ...
抱歉我的困惑问题:我想要一个可以通过点击链接到网页的超链接。所以我得到了完整的网址
web <- data.frame(sapply(answer$link, function(x) {paste("https://stackoverflow.com",x, sep = "")}))
或者
web <- data.frame(sapply(df[2], function(x) {paste("https://stackoverflow.com",x, sep = "")}))
web[1]
https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
喜欢 [这里] (如何制作一个出色的 R 可重现示例)
我将此文件输出到 txt 或 CSV,但是当我单击它时,链接无法链接页面。
你能改进它吗?再次感谢
@DaveT @QHarr
解决方案
您应该真正使用 API Stack 提供。但是,您可以使用一级 css 选择器来执行此操作,以a
按类属性收集标签,然后使用功能分离出来text
;然后也许会生成一个小标题...href
tidyverse
library(tidyverse)
library(rvest)
nodes <- read_html('https://stackoverflow.com/questions/tagged/r?tab=votes&page=1&pagesize=50')%>%html_nodes("[class=question-hyperlink]")
df <- map_df(nodes,~{
questions = .x %>% html_text()
links = paste0('https://stackoverflow.com',.x %>% html_attr("href") )
tibble(questions, links)
})
推荐阅读
- python - 在 pandas 中爆炸两列:ValueError
- amazon-s3 - Amazon S3 和 Amazon CloudFront 将服务证书迁移到 Amazon Trust Services
- javascript - 如何使用 alert() 在 JS 中显示数组元素?
- javascript - Flask:无法连接到虚拟服务器上的 REDIS
- c++ - 随机整数范围 0 到 100,结果总和也不能超过 100
- python - 从在线集群中的视频中提取帧的代码有什么问题?
- django - 如何将参数日期传递给 url 调度程序但作为命名参数
- sql - 您可以结合 case 和 top 语句来标记哪些值在前几个(Microsoft SQL)
- python - 格式化多维数组
- javascript - 有没有办法在导出对象的同时保留 JavaScript 中的变量?