【问题标题】:With XML query using R and XPath 1.0, unable to extract specific text使用 R 和 XPath 1.0 进行 XML 查询时,无法提取特定文本
【发布时间】:2014-09-11 13:19:27
【问题描述】:

非常感谢有关如何提取这家公司设有办事处的四个城市名称的指导。 Firebug 在 cufontext 下的名称是灰色的,例如 <cufontext>MEMPHIS</cufontext>,而 MEMPHIS 是灰色的。顺便说一句,我不介意返回一些无关的文本,例如状态或地址。展示了我的三个失败的努力。

library(XML)

doc <- htmlTreeParse('http://www.lewisthomason.com/locations/', useInternal = TRUE, asText = TRUE)               
xpathSApply(doc, "//div[@id = 'the_content']", xmlValue, trim = TRUE)  # returns list()
xpathSApply(doc, "//div[@id = 'the_content']/div/h3//cufon", xmlValue, trim = TRUE) # returns NULL
xpathSApply(doc, "//div[@id = 'the_content']//cufon[@class = 'cufon cufon-canvas']", xmlValue, trim = TRUE)  # returns NULL

非常感谢。

【问题讨论】:

  • 另外,rl &lt;- readLines(url); htmlTreeParse(rl, asText = TRUE) 似乎有效。
  • @RichardScriven:谢谢。从站点获取 HTML 不是问题。提取城市的 XPath 表达式阻碍了我和下面的建议答案。

标签: html xml r parsing xpath


【解决方案1】:

原来 HTML 源代码实际上看起来像这样(格式化和简化):

<div id="the_content">
    <div class="one_fourth">
        <h3>KNOXVILLE</h3>
        <p>One Centre Square, Fifth Floor<br>
        .....
    </div>
    ....
</div>

但浏览器(尝试使用 chrome 和 firefox)以某种方式将其转换为稍微不同的结构,而解析器不进行转换。这个更简单的 XPath 对我来说很好用:

//div[@id = 'the_content']/div/h3

【讨论】:

  • 谢谢。如果我从 Firebug 复制 HTML 源代码,我是否在 SO 中使用 {} 操作来格式化它(红色表示属性,蓝色表示“元素”并缩进?
  • > doc lewisthomason.com/locations', useInternal = TRUE, asText = TRUE) > xpathSApply(doc, "//div[@id = 'the_content']/div/h3" , xmlValue, trim = TRUE) NULL
  • 我对@9​​87654325@其实并不熟悉,只知道XPath。无论如何,在查看xmlTreeParse() 文档后(在任何地方都找不到htmlTreeParse() 的文档),asText=TRUE 将导致解析器将您的 url 视为 HTML(尝试打印 doc 变量以确认这一点)。跨度>
  • 我愿意接受你的回答,@har07,但它不起作用,如我上面的评论所示。
  • 为什么这次要设置asText=TRUE?我真的怀疑这会导致问题
猜你喜欢
  • 2013-06-12
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
相关资源
最近更新 更多