gpt4 book ai didi

r - R xpathSApply:获取节点文本而不从其子节点获取文本

转载 作者:行者123 更新时间:2023-12-03 16:58:35 28 4
gpt4 key购买 nike

我正在尝试从网站的一部分中提取文本。包含文本的div节点还包含几个子节点,每个子节点都有自己的文本或其他内容。但是,我只希望顶部节点中的文本而不是其子级中的文本!

这是相关页面部分的样子:

    <div class="body-text">
<div id="other" class="other"></div>
<div id="other2" class="other2"></div>
<div id="other3" class="other3">
<span>irrelevant text</span>
</div>

<h2>heading2</h2>

-Text which I want to get. There are also text parts which are linked.

</div>


这是我的代码,使我获得“混乱”文本。我尝试了 /text(),但是只要链接了一部分文本,它就会截断我的文本。所以我不能使用它。我也尝试过使用 /div/node()[not(self::div)]进行操作,但未能使其正常工作。有人可以帮忙吗?

webpage = getURL(url)
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
pagetree <- htmlTreeParse(webpage, useInternalNodes = TRUE, encoding='UTF-8')

body <- xpathSApply(pagetree, "//div[@class='body-text']", xmlValue)

最佳答案

1)发布示例

尝试在text()分区内搜索a/text()body-text的节点,删除所有仅包含空格的琐碎节点:

## input

Text <- '<div class="body-text">
<div id="other" class="other"></div>
<div id="other2" class="other2"></div>
<div id="other3" class="other3">
<span>irrelevant text</span>
</div>
<h2>heading2</h2>
-Text which I want to get. There are also text parts which are linked.
</div>'

library(XML)
pagetree <- htmlTreeParse(Text, asText = TRUE, useInternalNodes = TRUE)

## process it - xpth is the Xpath expression and xpathSApply() runs it

trim <- function(x) gsub("^\\s+|\\s+$", "", x) # trim whitespace from start & end

xpth <- "( //div[@class='body-text']/text() |
//div[@class='body-text']/a/text() ) [ normalize-space() != '' ]"
txt <- trim(xpathSApply(pagetree, xpth, xmlValue))


结果如下:

> txt
[1] "-Text which I want to get. There are also text parts which are linked."


2)张贴者在评论中提供的示例。将此用作 Text

Text <- '<div class="body-text"> text starts here 
<a class="footnote" href="link"> text continues here <sup>1</sup> </a>
and continues here</div>'


并重复上面的代码,我们得到:

> txt
[1] "text starts here" "text continues here" "and continues here"


编辑:根据海报的评论修改了以上内容。主要变化是xpath表达式, xpth和最终点,该点说明了与张贴者在注释中提供的示例相同的代码。

编辑:已将过滤操作从纯空白节点从R移到Xpath。这会稍微延长Xpath表达式的长度,但消除了R Filter()步骤。还简化并稍微减少了演示。

关于r - R xpathSApply:获取节点文本而不从其子节点获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8343760/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com