Nov*_*Nov 13 html r html-parsing xml-parsing
readLines函数在一行中显示源页面的所有内容.
con = url("target_url_here")
htmlcode = readLines(con)
Run Code Online (Sandbox Code Playgroud)
readLines函数在一行中连接了源页面的所有行.所以我无法导航到原始html源页面中的第15行.
接下来的方法是尝试使用XML包或httr包解析它.
library("httr")
html <- GET("target_url_here")
content2 = content(html,as="text")
parsedHtml = htmlParse(content2,asText=TRUE)
Run Code Online (Sandbox Code Playgroud)
通过打印出parsedHtml,它保留了html格式并显示了在源页面中可以看到的所有内容.现在假设我要提取标题,所以函数
xpathSApply(parsedHtml,"//title",xmlValue)
Run Code Online (Sandbox Code Playgroud)
将给出标题.
但我的问题是,如何导航到任何一行说html的第15行?换句话说,我如何将html视为字符串向量,其中向量的每个元素都是html页面/解析的html对象中的单独行.
Mar*_*tuc 16
具有更好看的文档的readLines(),它实际上返回:
长度为读取行数的字符向量.
所以在你的情况下:
con = url("http://example.com/file_to_parse.html")
htmlCode = readLines(con)
Run Code Online (Sandbox Code Playgroud)
您可以轻松地做htmlCode[15]访问15 日线在原有的HTML源页面.
回应你的评论
但有没有办法在解析的HTML对象中转到第15行?
有几种不同的方法可以做到这一点.lukeA在评论中提到了一个.另一种方法是使用capture.output()逐行获取解析后的html文档作为字符向量.此示例使用来自的示例数据?htmlParse
library(XML)
f <- system.file("exampleData", "9003.html", package = "XML")
Run Code Online (Sandbox Code Playgroud)
解析一个html文档:
( doc <- htmlParse(f) )
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# <html xmlns="http://www.w3.org/1999/xhtml">
# <head>
# <meta name="generator" content="HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">
# <title>BKA/RIS VwGH - Volltext</title>
# <base target="_self">
# </head>
# <body>
# Veröffentlichungsdatum
# </body>
# </html>
Run Code Online (Sandbox Code Playgroud)
将解析的文档视为字符向量:
capture.output(doc)
# [1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">"
# [2] "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
# [3] "<head>"
# [4] "<meta name=\"generator\" content=\"HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org\">"
# [5] "<title>BKA/RIS VwGH - Volltext</title>"
# [6] "<base target=\"_self\">"
# [7] "</head>"
# [8] "<body>"
# [9] "Veröffentlichungsdatum"
# [10] "</body>"
# [11] "</html>"
# [12] " "
Run Code Online (Sandbox Code Playgroud)
得到(例如)第5行:
capture.output(doc)[5]
#[1] "<title>BKA/RIS VwGH - Volltext</title>"
Run Code Online (Sandbox Code Playgroud)