You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用rvest爬取页面时html_attr获取href链接不完整如何解决

解决方案

你遇到的相对链接拼接问题不需要手动研究/sk####的规则,直接用xml2包内置的url_absolute()函数就可以自动基于当前请求的页面URL完成相对路径到绝对路径的转换,自动适配不同页面的前缀变化。

代码修改逻辑如下:

  • 拿到href属性后新增一步路径转换,用当前爬取页面的原始URL作为基准路径自动拼接
  • 可以增加文本过滤逻辑,只保留你需要的Relazione和Testo articoli对应的链接,避免拿到无效内容

修改后的完整可运行代码:

# 提前安装加载依赖包:install.packages(c("rvest","pbapply","xml2"))
library(rvest)
library(pbapply)
library(xml2)

df <- structure(list(date = c(20010618L, 20010618L, 20010618L, 20010618L, 
                        20010618L), link = c("http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=814", 
                                                  "http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=858", 
                                                  "http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=875", 
                                                  "http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=802", 
                                                  "http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=816"
                        )), row.names = c(NA, 5L), class = "data.frame")


df$linkfinal<- pbsapply(df$link, function(x) {
  tryCatch({
    read_html(x) %>%
      html_nodes('td+ td a') %>%
      # 过滤仅保留目标链接
      .[html_text(.) %in% c("Relazione", "Testo articoli")] %>%
      html_attr("href") %>% 
      # 自动拼接为完整绝对路径,适配所有sk前缀变化
      url_absolute(base = x) %>%
      toString()
  }, error = function(e) NA)
})

可选调整:如果你不需要把两个链接拼成字符串,可以去掉toString(),将linkfinal设置为列表列,每个位置单独存储两个目标链接,方便后续单独调用。

内容的提问来源于stack exchange,提问作者Alberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:15:01