在rvest中使用CSS选择器:first/:last为何返回错误?
解决rvest中CSS选择器
:last报错的问题 问题原因
Selector Gadget的:last是其自定义的非标准伪类,而rvest依赖的Chrome DevTools Protocol仅支持标准CSS选择器,因此会触发DOM查询错误。你尝试的:nth-last-child(1)无效,可能是因为目标按钮并非其父元素的最后一个子元素(比如父元素下还有其他类型的元素)。
解决方案
方案1:使用标准CSS伪类:last-of-type
:last-of-type是标准CSS伪类,用于选择父元素下最后一个指定类型的子元素。调整选择器为:
page <- read_html_live("https://researchers.cedars-sinai.edu/search?by=text&type=user") # 定位最后一个按钮 page %>% html_elements("span button:last-of-type") # 点击最后一个按钮 page$click(css = "span button:last-of-type")
如果按钮是span的直接子元素,可加上子元素选择符>提高精度:
page$click(css = "span > button:last-of-type")
方案2:先获取所有按钮再取最后一个
如果标准伪类仍不生效,可先获取页面中所有目标按钮,再通过索引选取最后一个并点击:
page <- read_html_live("https://researchers.cedars-sinai.edu/search?by=text&type=user") # 获取所有符合条件的按钮 all_buttons <- page %>% html_elements("span button") # 选取最后一个按钮并点击 if (length(all_buttons) > 0) { all_buttons[[length(all_buttons)]]$click() }
这种方法无需依赖复杂的CSS选择器,兼容性更强。
内容的提问来源于stack exchange,提问作者a.sa.5969
相关产品推荐
相关产品推荐

