首页 > 解决方案 > 如何获取选择菜单的值?

问题描述

我正在尝试获取此网页上选择菜单的值(所有区域) 。我有什么错?几乎尝试了所有组合,但结果为零。其中之一是:

  page <- read_html("https://www.yemeksepeti.com/en/istanbul")
  regions <- page %>% 
    html_nodes("div") %>% 
    html_nodes("span") %>% 
    html_nodes(xpath = '//*[@id="select2-ys-areaSelector-container"]') %>% 
    html_attr("title")

提前致谢。

标签: htmlrweb-scrapingrvest

解决方案


XPath 是一种丑陋的野兽。获取select元素的 id,然后获取所有选项组,最后获取它们的文本数据。用于html_text将其转换为 R character

page <- read_html("https://www.yemeksepeti.com/en/istanbul")
regions <- page %>% 
  html_nodes(xpath='//*[@id="ys-areaSelector"]/optgroup/*/text()') %>%
  html_text()

推荐阅读