Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rvest - scrape 2 classes in 1 tag

I am new to rvest. How do I extract those elements with 2 class names or only 1 class name in tag?

This is my code and issue:

doc <- paste("<html>",
             "<body>",
             "<span class='a1 b1'> text1 </span>",
             "<span class='b1'> text2 </span>",
             "</body>",
             "</html>"
            )
library(rvest)
read_html(doc) %>% html_nodes(".b1")  %>% html_text()
#output: text1, text2
#what i want: text2

#I also want to extract only elements with 2 class names
read_html(doc) %>% html_nodes(".a1 .b1") %>% html_text()
# Output that i want: text1

This is my machine spec:

Operation System: Windows 10.

rvest version: 0.3.2

R version 3.3.3 (2017-03-06)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Anybody can help?

like image 468
addicted Avatar asked Aug 02 '17 03:08

addicted


1 Answers

You can use css selector as follows:

Select class contains b1 not a1:

read_html(doc) %>% html_nodes(".b1:not(.a1)")
# {xml_nodeset (1)}
# [1] <span class="b1"> text2 </span>

Or use the attribute selector:

read_html(doc) %>% html_nodes("[class='b1']")
# {xml_nodeset (1)}
# [1] <span class="b1"> text2 </span>

Select class contains both:

read_html(doc) %>% html_nodes(".a1.b1")
# {xml_nodeset (1)}
# [1] <span class="a1 b1"> text1 </span>
like image 95
Psidom Avatar answered Oct 17 '22 10:10

Psidom