首页 > 解决方案 > rvest - 仅选择类下的某些 href

问题描述

客观的

抓取指向零售商店位置的文件路径向量,同时忽略超链接的电话号码。我是使用 html 元素的新手。

我试过的

library(rvest)
library(tidyverse)
library(xml2)

store.paths <- read_html("https://www.walmart.com/store/directory/al/alabaster") %>%
    html_nodes(xpath = '//*[@class="store-directory-container"]') %>% 
    html_nodes("a") %>% 
    html_attr('href') 

产生

[1] "/store/4756"      "tel:205-624-6229" "/store/423"       "tel:205-620-0360"

而我的愿望输出是

[1] "/store/4756"  "/store/423"

我尝试替换store-directory-containerstoreBanner,结果为空。

谢谢!

标签: htmlrrvest

解决方案


看起来a你想要的标签也有类storeBanner,而电话链接没有。很容易抓住它们

store.paths <- read_html("https://www.walmart.com/store/directory/al/alabaster") %>%
  html_elements("a.storeBanner") %>% 
  html_attr('href') 

在这种情况下,我还使用了 CSS 选择器语法,因为它更简单,并且使用推荐html_elements功能,因为html_nodes它已被软弃用。您不能只用“storeBanner”替换“store-directory-container”,因为“a”标签位于“store-directory-container”下方,但在“storeBanner”的情况下,它是那个元素,而不是子元素那个元素。


推荐阅读