【问题标题】:R Read & Parse HTML to ListR读取并解析HTML到列表
【发布时间】:2016-12-18 20:20:28
【问题描述】:

我一直在尝试阅读和解析一些 HTML,以获取动物收容所的动物状况列表。我确信我对 HTML 解析的缺乏经验并没有帮助,但我似乎没有得到什么快。

这是 HTML 的 sn-p:

<select multiple="true" name="asilomarCondition" id="asilomarCondition">

    <option value="101">
        Behavior- Aggression, Confrontational-Toward People (mild)
        -
        TM</option>
....
</select>

标签只有一个&lt;select...&gt;,其余的都是&lt;option value=x&gt;

我一直在使用 XML 库。我可以删除换行符和制表符,但没有成功删除标签:

conditions.html <- paste(readLines("Data/evalconditions.txt"), collapse="\n")
conditions.text <- gsub('[\t\n]',"",conditions.html)

作为最终结果,我想要一份我可以进一步处理的所有条件的列表,以供以后用作因子名称:

Behavior- Aggression, Confrontational-Toward People (mild)-TM
Behavior- Aggression, Confrontational-Toward People (moderate/severe)-UU
...

我不确定是否需要使用 XML 库(或其他库),或者 gsub 模式是否足够(无论哪种方式,我都需要弄清楚如何使用它)。

【问题讨论】:

  • 你能用那个选择框指向完整的 URL 或者扩展一下 sn-p 吗?
  • 我发现 rvest 包更易于使用。如果您可以提供该网站的链接,那么有人可以编写您的解决方案。
  • 它是 HTML。这是@alistaire 形式的选择列表
  • 哎呀,真的。 library(rvest) ; html %&gt;% read_html() %&gt;% html_nodes('option') %&gt;% html_text(trim = TRUE)
  • 很遗憾,我无法提供网址。它是一个只有用户访问权限的在线 DBMS。我是收容所的一名志愿者,试图帮助进行一些数据分析。我可以拉整个页面,但那里可能有敏感数据。我只是拿了一个动物实例来获得我需要的部分。如果有用的话,我可以发布我拉的整个 sn-p。不过,我会查看 rvest 库!

标签: r html-parsing


【解决方案1】:

这里是使用 rvest 包的开始:

library(rvest)
#read the html page
page<-read_html("test.html")
#get the text from the "option" nodes and then trim the whitespace
nodes<-trimws(html_text(html_nodes(page, "option")))

#nodes will need additional clean up to remove the excessive spaces 
#and newline characters
nodes<-gsub("\n", "", nodes)
nodes<-gsub("  ", "", nodes)

矢量节点应该是您要求的结果。此示例基于上面提供的有限示例,实际页面可能会出现意想不到的结果。

【讨论】:

  • 谢谢,@Dave2e!这非常有效!我还有一些额外的字符要清理,但是用你的例子很容易做到。继续进行其余的数据清理! :o
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2014-03-18
  • 2017-05-18
  • 2016-09-16
  • 2021-11-26
  • 2017-03-30
相关资源
最近更新 更多