How can I select all <div> without a class or id with rvest?

Viewed 513

Take the following HTML snippet, read in with rvest:

page <- read_html('<div class="author">A name</div>
<div id="tag">A tag</div>
<div>A number</div>
<div>A date</div>
<p class="articleParagraph dearticleParagraph">A text</p>
')

I can select all the <div> nodes like this:

page %>% html_nodes("div")

How do I select only those <div> nodes that do not have any class or id, i.e. not the first two?


Building on the first comment, I have made some progress:

page %>% html_nodes("div:not([class])")

excludes the first div, as desired.

page %>% html_nodes("div:not([id])")

excludes the second div, as desired.

However, I cannot combine the two:

page %>% html_nodes("div:not([class])") %>% html_nodes("div:not([id])")

returns an empty node set.

1 Answers

I used xpath with the not() function and or

library(rvest)
page <- read_html('<div class="author">A name</div>
                   <div id="tag">A tag</div>
                   <div>A number</div>
                   <div>A date</div>
                   <p class="articleParagraph dearticleParagraph">A text</p>')

page %>% html_nodes('div')
# {xml_nodeset (4)}
# [1] <div class="author">A name</div>
# [2] <div id="tag">A tag</div>
# [3] <div>A number</div>
# [4] <div>A date</div>

# XPATH version:
page %>% html_nodes(xpath = '//div[not(@id or @class)]')
# {xml_nodeset (2)}
# [1] <div>A number</div>
# [2] <div>A date</div>

# CSS version:
page %>% html_nodes('div:not([id]):not([class])')
# {xml_nodeset (2)}
# [1] <div>A number</div>
# [2] <div>A date</div>

# Maybe this is what you are looking for too?
page %>% html_nodes(':not([id]):not([class])')
# {xml_nodeset (3)}
# [1] <body>\n<div class="author">A name</div>\n<div id="tag">A tag</div>\n<div>A number</d ...
# [2] <div>A number</div>
# [3] <div>A date</div>
Related