Switch branches/tags
Find file Copy path
f6428be Nov 20, 2015
2 contributors

Users who have contributed to this file

@hadley @sfirke
104 lines (77 sloc) 3.94 KB
title author date output vignette
Hadley Wickham
`r Sys.Date()`
%\VignetteIndexEntry{Selectorgadget} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8}
embed_png <- function(path, dpi = NULL) {
  meta <- attr(png::readPNG(path, native = TRUE, info = TRUE), "info")
  if (!is.null(dpi)) meta$dpi <- rep(dpi, 2)

    "<img src='", path, "'",
    " width=", round(meta$dim[1] / (meta$dpi[1] / 96)),
    " height=", round(meta$dim[2] / (meta$dpi[2] / 96)),
    " />"

knitr::opts_chunk$set(comment = "#>", collapse = TRUE)

Selectorgadget is a javascript bookmarklet that allows you to interactively figure out what css selector you need to extract desired components from a page.


To install it, open this page in your browser, and then drag the following link to your bookmark bar: SelectorGadget.


To use it, open the page

  1. Click on the element you want to select. Selectorgadget will make a first guess at what css selector you want. It's likely to be bad since it only has one example to learn from, but it's a start. Elements that match the selector will be highlighted in yellow.

  2. Click on elements that shouldn't be selected. They will turn red. Click on elements that should be selected. They will turn green.

  3. Iterate until only the elements you want are selected. Selectorgadget isn't perfect and sometimes won't be able to find a useful css selector. Sometimes starting from a different element helps.

For example, imagine we want to find the actors listed on an IMDB movie page, e.g. The Lego Movie.

  1. Navigate to the page and scroll to the actors list.

  2. Click on the selectorgagdget link in the bookmarks. The selectorgadget console will appear at the bottom of the screen, and element currently under the mouse will be highlighed in orange.

  3. Click on the element you want to select (the name of an actor). The element you selected will be highlighted in green. Selectorgadget guesses which css selector you want (.itemprop in this case), and highlights all matches in yellow.

  4. Scroll around the document to find elements that you don't want to match and click on them. For example, we don't to match the title of the movie, so we click on it and it turns red. The css selector updates to #titleCast .itemprop.


Once we've determined the css selector, we can use it in R to extract the values we want:

html <- read_html("")
cast <- html_nodes(html, "#titleCast .itemprop")

Looking carefully at this output, we see twice as many matches as we expected. That's because we've selected both the table cell and the text inside the cell. We can experiment with selectorgadget to find a better match or look at the html directly.

cast <- html_nodes(html, "#titleCast span.itemprop")