如何使用R与rvest提取标签onclick属性中的URL路径?
解决rvest获取onclick属性内容的问题
问题本质:
html_text2()是提取元素的文本内容,而onclick是元素的属性,所以用这个方法根本拿不到属性值,得用专门读取属性的函数。具体解决步骤:
- 选中目标元素后,调用
html_attr("onclick")直接获取该属性的完整内容 - 对属性值做正则提取,剥离出目标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
相关产品推荐
相关产品推荐

