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

如何使用R与rvest提取标签onclick属性中的URL路径?

解决rvest获取onclick属性内容的问题
  • 问题本质:html_text2()是提取元素的文本内容,而onclick是元素的属性,所以用这个方法根本拿不到属性值,得用专门读取属性的函数。

  • 具体解决步骤:

    1. 选中目标元素后,调用html_attr("onclick")直接获取该属性的完整内容
    2. 对属性值做正则提取,剥离出目标URL路径

示例代码:

library(rvest)
library(stringr)

# 加载目标页面
target_url <- "https://www.forklift-international.com/en/for-sale/forklift-battery"
page_content <- read_html(target_url)

# 选中卡片元素并提取onclick属性
card_elements <- page_content %>% html_elements(".card.cardhighlight0")
onclick_content <- card_elements %>% html_attr("onclick")

# 正则提取URL路径(适配类似goTo('/xxx/xxx')的格式)
extracted_paths <- str_extract(onclick_content, "'([^']+)'") %>% 
  str_remove_all("'")

# 拼接为完整可访问的URL
full_urls <- paste0("https://www.forklift-international.com", extracted_paths)
  • 注意:如果页面里的onclick属性用的是双引号包裹路径,把正则里的单引号换成双引号即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:32:38