Rvest extract option value and text from select

杀马特。学长 韩版系。学妹 提交于 2019-12-10 18:26:47

问题


Rvest select option, I think it is easiest to explain with an example reproducible

Website: http://www.verema.com/vinos/portada I want to get the types of wines (Tipos de vinos), in html code is:

<select class="campo select" id="producto_tipo_producto_id" name="producto[tipo_producto_id]">
<option value="">Todos</option>
<option value="211">Tinto</option>
<option value="213">Blanco</option>
<option value="215">Rosado</option>
<option value="216">Espumoso</option>
<option value="217">Dulces y Generosos</option></select>

XPath :  //*[@id="producto_tipo_producto_id"]  or
CSS : #producto_tipo_producto_id  or
Class: campo select

I want a data.frame as

211 Tinto

213 Blanco

215 Rosado

216 Espumoso

217 Dulces y Generosos

My code (R):

library(rvest)

Pagina.R <- html(x = "http://www.verema.com/vinos/portada")

text <- Pagina.R %>% 
  html_nodes(xpath='//*[@id="producto_tipo_producto_id"]')%>%
  html_text() 
text

values <- Pagina.R %>% 
  html_nodes(xpath='//*[@id="producto_tipo_producto_id"]')%>%
  html_attr("option value")       #problem????
values

Res <- data.frame(text = text, values = values, stringsAsFactors = FALSE)
Res  # problem  

Suggestions?

Thank you.


Update

Revised, functioning code:

library(rvest)

Pagina.R <- html(x = "http://www.verema.com/vinos/portada")

text <- Pagina.R %>% 
#  html_nodes(xpath='//*[@id="producto_tipo_producto_id"]')%>%
  html_nodes(xpath='//*[@id="producto_tipo_producto_id"]/option')%>%
  html_text() 
text

values <- Pagina.R %>% 
#  html_nodes(xpath='//*[@id="producto_tipo_producto_id"]')%>%
  html_nodes(xpath='//*[@id="producto_tipo_producto_id"]/option')%>%
   # html_attr("option value") 
  html_attr("value") 
values

Res <- data.frame(text = text, values = values, stringsAsFactors = FALSE)
Res 

来源:https://stackoverflow.com/questions/31615435/rvest-extract-option-value-and-text-from-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!