rvest package read_html() 函数在“<”符号处停止读取

rvest package read_html() function stops reading at "<" symbol

我想知道 rvest 包中是否有此行为。当 rvest 看到 < 字符时,它停止读取 HTML。

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

打印:

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

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

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

请参阅 w3schools HTML Entities 页面。 <> 是 html 中的保留字符,它们的字面值必须以另一种方式书写,作为特定的字符实体。这是链接页面中的实体 table,给出了一些常用的 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.

的其他包