Search code examples
rweb-scrapingxpath

R, Xpath, Scrape


I want to scrape a website using Xpath references and R. I am new to this, but as far as I learned, I write the following code,,

 A <- "http://www.strompreis.elcom.admin.ch/ShowCat.aspx?placeNumber=5661&OpID=2&Period=2015"
 doc <- htmlParse(A)
 A <- xpathApply(A,path="//tr[1]/td/span",fun=xmlAttrs)

However, I got the following error,

Error in UseMethod("xpathApply") : 
  no applicable method for 'xpathApply' applied to an object of class "character"

I am interested in scaping the following xpath: //tr[1]/td/span What is the problem? What's worng with the code?


Solution

  • Using rvest, this seems to work:

    library(rvest)
    A="http://www.strompreis.elcom.admin.ch/ShowCat.aspx?placeNumber=5661&OpID=2&Period=2015"
    A %>% html() %>% html_nodes(xpath="//tr[1]/td/span") %>% html_text()