html - 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-container
为storeBanner
,结果为空。
谢谢!
解决方案
看起来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”的情况下,它是那个元素,而不是子元素那个元素。
推荐阅读
- python - 读取 CSV 文件并提取特定数据
- java - 无法在 Java Web 项目中运行 Java 文件
- python - Java 中的 try catch 结构与 Python 中的 try except 相比如何?
- javascript - console.log 没有正确显示 React 状态
- python - Boto3 wait_until_exists 可用图像(对象没有属性)
- svg - 旋转的矩形与文本 bbox 不匹配
- node.js - .then 语句不按顺序执行
- java - 使用扫描仪实现循环单链表
- wordpress - 迁移:迁移后的上一个 URL 重定向
- r - JASP 上的贝叶斯 T 检验和贝叶斯信息假设评估 (BAIN) 之间的区别?