title: R How to Check if XPath Exists
body: <p>hoping someone more knowledgeable than me can throw some light here.</p>
  
  <p>As part of a larger web-scraper I want to pull meta data out of a set of pages.  When I ran this it fell over, investigation shows this was due to one of the Xpath's being requested not existing.</p>
  
  <p>I can see one potential solution is to grab ALL the meta for a page into a vector and to check if each required one exists before building a new vector of just those I want.</p>
  
  <p>BUT</p>
  
  <p>It would be even better if I only grabbed the bits I want if they exist in the page.</p>
  
  <pre><code>require(XML)
  require(RCurl)
  parsed &lt;- htmlParse("http://www.coindesk.com/information")
  
  meta &lt;- list()
  meta[1] &lt;- xpathSApply(parsed, "//meta[starts-with(@property, \"og:title\")]", xmlGetAttr,"content")
  meta[2] &lt;- xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]", xmlGetAttr,"content")
  meta[3] &lt;- xpathApply(parsed, "//meta[starts-with(@property, \"og:url\")]",  xmlGetAttr,"content")
  meta[4] &lt;- xpathApply(parsed, "//meta[starts-with(@property, \"article:published_time\")]",  xmlGetAttr,"content")
  meta[5] &lt;- xpathApply(parsed, "//meta[starts-with(@property, \"article:modified_time\")]",  xmlGetAttr,"content")
  </code></pre>
  
  <p>This will throw an error as <code>og:description</code> isn't in this page.</p>
  
  <pre><code>Error in meta[2] &lt;- xpathApply(parsed, "//meta[starts-with(@property, \"og:description\")]",  : 
    replacement has length zero
  </code></pre>
  
  <p>Can anyone suggest a simple test that will check for its existence before trying to extract it, falling over gracefully with perhaps a NULL response?</p>