rvest-在1个标签中抓取2个类 [英] rvest - scrape 2 classes in 1 tag

查看:61
本文介绍了rvest-在1个标签中抓取2个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是rvest的新手.如何在标记中使用2个类名或仅1个类名提取这些元素?

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

这是我的代码和问题:

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

这是我的机器规格:

操作系统:Windows 10.

Operation System: Windows 10.

最佳版本:0.3.2

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)

有人可以帮忙吗?

推荐答案

您可以按如下方式使用css选择器:

You can use css selector as follows:

选择类包含 b1 而不是 a1 :

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

或使用属性选择器:

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

选择类同时包含:

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

这篇关于rvest-在1个标签中抓取2个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆