首页 > 解决方案 > 如何通过 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

标签: rweb-scrapinghyperlink

解决方案


您应该真正使用 API Stack 提供。但是,您可以使用一级 css 选择器来执行此操作,以a按类属性收集标签,然后使用功能分离出来text;然后也许会生成一个小标题...hreftidyverse

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)
})

在此处输入图像描述


推荐阅读