【问题标题】:rvest package read_html() function stops reading at "<" symbolrvest 包 read_html() 函数在“<”符号处停止读取
【发布时间】:2016-01-31 13:39:15
【问题描述】:

我想知道rvest 包中是否有这种行为。当rvest 看到&lt; 字符时,它会停止读取HTML。

library(rvest)
read_html("<html><title>under 30 years = < 30 years <title></html>")

打印:

[1] <head>\n  <title>under 30 = </title>\n</head>

如果这是故意的,是否有解决方法?

【问题讨论】:

  • 解决方法是停止使用无效的 HTML。
  • 您并不总是能够选择您正在阅读的 HTML。
  • 当然,这就是为什么 rvest 不会在错误的 sn-p 上失败,但会产生最佳猜测。浏览器也是如此。

标签: html r html-parsing rvest


【解决方案1】:

是的,rvest 是正常的,因为 html 是正常的。

请参阅w3schools HTML Entities 页面。 &lt;&gt; 是 html 中的保留字符,它们的文字值必须以另一种方式写入,作为特定的字符实体。这是链接页面中的实体表,给出了一些常用的 html 字符及其各自的 html 实体。

XML::readHTMLTable("http://www.w3schools.com/html/html_entities.asp", which = 2)
#    Result          Description Entity Name Entity Number
# 1           non-breaking space      &nbsp;        &#160;
# 2       <            less than        &lt;         &#60;
# 3       >         greater than        &gt;         &#62;
# 4       &            ampersand       &amp;         &#38;
# 5       ¢                 cent      &cent;        &#162;
# 6       £                pound     &pound;        &#163;
# 7       ¥                  yen       &yen;        &#165;
# 8       €                 euro      &euro;       &#8364;
# 9       ©            copyright      &copy;        &#169;
# 10      ® registered trademark       &reg;        &#174;

因此,您将不得不替换这些值,可能使用gsub() 或手动替换(如果没有太多)。可以看到,当这些字符被替换为正确的实体时,它会正确解析。

library(XML)
doc <- htmlParse("<html><title>under 30 years = &lt; 30 years </title></html>")
xmlValue(doc["//title"][[1]])
# [1] "under 30 years = < 30 years "

您可以使用gsub(),类似于以下内容

txt <- "<html><title>under 30 years = < 30 years </title></html>"
xmlValue(htmlParse(gsub(" < ", " &lt; ", txt, fixed = TRUE))["//title"][[1]])
# [1] "under 30 years = < 30 years "

我在这里使用了 XML 包,但同样适用于处理 html 的其他包。

【讨论】:

  • rvest 现在基于xml2 而不是xml
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多