html - 如何使用 htmlParse 和 xpathSApply 获取 html 中 <meta name...> 标记内的信息

标签 html xml r

我有很多网页,我想提取它们的发布日期。 对于某些网页,日期位于“abbr”标签中(例如:abbr class=\"published\"title=\"2012-03-14T07:13:39+00:00\">2012-03-14, 7:13"),我可以使用以下方法获取日期: doc=htmlParse(theURL,asText=T) xpathSApply(doc,"//abbr",xmlValue)

但对于其他网页,日期位于“mega”标签中,例如:
元名称=\"已创建\"内容=\"2011-12-29T11:49:23+00:00\"
元名称=\“原始发布日期\”内容=\“2012/11/14 10:56:58\”

我尝试了 xpathSApply(doc, "//meta",xmlValue),但它不起作用。

那么,我应该使用什么模式来代替“//meta”?

谢谢!

最佳答案

以此页面为例:

library(XML)
url <- "http://stackoverflow.com/questions/22342501/"
doc <- htmlParse(url, useInternalNodes=T)
names   <- doc["//meta/@name"]
content <- doc["//meta/@content"]
cbind(names,content)
#      names            content                                                                                                           
# [1,] "twitter:card"   "summary"                                                                                                         
# [2,] "twitter:domain" "stackoverflow.com"                                                                                               
# [3,] "og:type"        "website"                                                                                                         
# [4,] "og:image"       "http://cdn.sstatic.net/stackoverflow/img/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b5a4a4b8b1f9a0bba1b7bcf9bdb7bbba94e6faa4bab3" rel="noreferrer noopener nofollow">[email protected]</a>?v=fde65a5a78c6"                                  
# [5,] "og:title"       "how to get information within <meta name...> tag in html using htmlParse and xpathSApply"                        
# [6,] "og:description" "I have a bunch of webpages and I want to extract their publishing dates. \nFor some webpages, the da" [truncated]
# [7,] "og:url"         "http://stackoverflow.com/questions/22342501/how-to-get-information-within-meta-name-tag-in-html-usi" [truncated] 

问题

xpathSApply(doc, "//meta",xmlValue)

xmlValue(...)返回元素内容(例如,元素的文本部分)。 <meta>标签没有文字。

关于html - 如何使用 htmlParse 和 xpathSApply 获取 html 中 &lt;meta name...> 标记内的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22342501/

相关文章:

python - 使用lxml添加一个字符串作为子元素

c# - 将 Java Map<string, string> 从 XML 解析为 C# 对象

r - 将同义词链接到通用标识符

r - R ggplot中热图中的聚类数据

javascript - Alpine JS 表格数据绑定(bind)

javascript - jQuery UI 可排序 : how to leave css values of changed items untouched?

java - 从 2000 行文件中提取数据的 Java XML 解析器(在移动设备上)

r - 当我尝试将数据框与混合数据类型融合时,我得到了 NA。我怎样才能最好地解决这个问题?

html - 将文字转换为纯文本(X)HTML的最简单方法或最佳工具

PHP 显示每个 div 的一定数量的记录