rvest - scrape 2 classes in 1 tag

非 Y 不嫁゛ 提交于 2019-12-10 06:47:17

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/45450981/rvest-scrape-2-classes-in-1-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!