我想解析这个 HTML: 并从中获取这个元素:
a) p
标签,与class: "normal_encontrado"
.
b) div
with class: "price"
.
有时,p
某些产品中不存在标签。如果是这种情况,NA
应添加到从该节点收集文本的向量中。
这个想法是有两个长度相同的向量,然后将它们连接起来以形成一个data.frame
。有任何想法吗?
HTML 部分:
<html>
<head></head>
<body>
<div class="product_price" id="product_price_186251">
<p class="normal_encontrado">
S/. 2,799.00
</p>
<div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
S/. 2,299.00
</div>
</div>
<div class="product_price" id="product_price_232046">
<div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
S/. 4,999.00
</div>
</div>
</body>
</html>
R Code:
library(rvest)
page_source <- read_html("r.html")
r.precio.antes <- page_source %>%
html_nodes(".normal_encontrado") %>%
html_text()
r.precio.actual <- page_source %>%
html_nodes(".price") %>%
html_text()
使用 XML 包解析输入xmlTreeParse
然后使用xpathSApply
迭代product_price
class div
节点。对于每个这样的节点,匿名函数获取div
and p
子节点。得到的字符矩阵m
被重新加工成数据框DF
并且列被清理,删除所有不是点或数字的字符,并删除所有点后跟非数字。将结果转换为数字。注意,对于缺失的部分没有特殊处理p
需要案例。
# input
Lines <- '<html>
<head></head>
<body>
<div class="product_price" id="product_price_186251">
<p class="normal_encontrado">
S/. 2,799.00
</p>
<div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
S/. 2,299.00
</div>
</div>
<div class="product_price" id="product_price_232046">
<div id="WC_CatalogEntryDBThumbnailDisplayJSPF_10461_div_10" class="price">
S/. 4,999.00
</div>
</div>
</body>
</html>'
# code to read input and produce a data.frame
library(XML)
doc <- xmlTreeParse(Lines, asText = TRUE, useInternalNodes = TRUE)
m <- xpathSApply(doc, "//div[@class = 'product_price']", function(node) {
list(p = xmlValue(node[["p"]]), div = xmlValue(node[["div"]])) })
DF <- as.data.frame(t(m), stringsAsFactors = FALSE) # rework into data frame
DF[] <- lapply(DF, function(x) as.numeric(gsub("[^.0-9]|[.]\\D", "", x))) # clean
结果是:
> DF
p div
1 2799 2299
2 NA 4999
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)