【问题标题】:Parsing HTML to text with link-tags remaining in R将 HTML 解析为带有 R 中保留的链接标签的文本
【发布时间】:2017-08-24 13:26:17
【问题描述】:

我的问题

我正在尝试将 HTML 文件(通过 Google Drive API 下载为 text/html)解析为 R 中的列表。

HTML 看起来像这样(对德语内容感到抱歉):

<p style='padding:0;margin:0;color:#000000;font-size:11pt;font-
family:"Arial";line-height:1.15;orphans:2;widows:2;text-align:left'>
<span>text: Das </span>
<span style="color:#1155cc;text-decoration:underline"><a 
href="https://www.google.com/url?q=http://www.bundesverfassungsgericht.de/SharedDocs/Entscheidungen/DE/2011/10/rs20111012_2bvr023608.html&amp;sa=D&amp;ust=1503574789125000&amp;usg=AFQ
jCNE4Ij3mvMX-QttYQYqspAaMxaZaeg" style="color:inherit;text-
decoration:inherit">Verfassungsgericht urteilt</a></span>
<span style='color:#000000;font-weight:400;text-
decoration:none;vertical-align:baseline;font-size:11pt;font-
family:"Arial";font-style:normal'>, 
dass eindeutig private Kommunikation von der Überwachung ausgenommen 
sein muss</span></p>

当我尝试使用以下方法从 xmlValues(XML 库)中提取文本时效果很好:

doc <- htmlParse(html, asText = TRUE)
text <- xpathSApply(doc, "//text()", xmlValue)

但就我而言,我需要在 HTML 文件中保留链接 (&lt;a&gt;-tags),并删除 https://www.google.com/url?q=-部分。所以我想摆脱所有样式,只保留文本+链接标签。

到目前为止我尝试了什么

我尝试通过在 XPath 中使用 //(p | a) 来获取这两个节点,但没有成功。

【问题讨论】:

    标签: html r xml xpath


    【解决方案1】:

    我更喜欢使用rvest 包而不是XML

    在这段代码中,我使用 rvest 包来解析 html 并从页面中提取链接。然后使用 stringr 包,我在 ?q= 部分拆分链接文本并返回原始链接的后半部分。

    library(rvest)
    library(stringr)
    
    #Read html file, 
    page<-read_html("sample.txt") 
    
    #then find the link nodes, then extract the attribute text (ie the links)
    link<-page%>% html_nodes("a") %>% html_attr( "href")
    #return second string of first list element 
    #(Use sapply if there are more than 1 link in document)
    desiredlink<-str_split(link, "\\?q=")[[1]][2]
    
    #Find the text in all of the span nodes
    span_text<-page%>% html_nodes("span") %>% html_text()
    # or this for the text under the p nodes
    p_text<-page%>% html_nodes("p") %>% html_text()
    

    我已将上面的示例 html 代码保存到文件中:“sample.txt”

    【讨论】:

    • 嘿 Dave2e,感谢您的回答。这有助于我在没有 google 部分的情况下获得链接。但是我仍然需要一些技巧来从完整的 html 中获取所有文本,对吧?
    • @BenedictWitzenberger,请参阅上面的编辑。 span_text 或 p_text 都应包含您要查找的附加信息。
    猜你喜欢
    • 2019-05-18
    • 2023-03-26
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多