【问题标题】:HTML scraping - R scrapRHTML 抓取 - R scrapR
【发布时间】:2014-06-28 18:35:40
【问题描述】:

我正在尝试解析以 HTML 格式编码的数据。我试图解析的字符串示例是:

Simplify the polynomial by combining like terms. <img src=\"/flx/math/inline/3x%2B12-11x%2B14\" class=\"x-math\" alt=\"3x+12-11x+14\" />

我想获取&lt;img之前的文字和alt=中的文字

期望的输出:

Simplify the polynomial by combining like terms. 3x+12-11x+14  

我试过scrapeR。

y1 = scrape (str1)  # the above string is in str1 (as a vector)

我收到以下错误消息

Error in which(value == defs) : 
  argument "code" is missing, with no default

有人玩过scrapeR吗?我不确定“代码”指的是什么,因为它是一个选项 并且在手册中没有描述。只是想看看哪个默认值会影响这一点。

【问题讨论】:

  • scrape 函数根据文档通常将 URL 作为它的第一个未命名参数。 y1 = scrape(object="str1")呢?
  • 它接受 str1。 y1=scrape(str1) 产生错误。 y1=scrape (object=str1) 会产生另一种错误 - 无法定位对象 str1。我认为 object=xxx 适用于带有 URL 等的对象。
  • 应该是y = scrape(object="str1") 而不是y1 = scrape(object=str1)。请参阅文档:rdocumentation.org/packages/scrapeR/functions/scrape
  • y = scrape(object="str1") 将整个 HTML 包装器放在 y 中。它现在有 等。它现在是一个完整的 HTML 文件。 (我期待相反的结果。(感谢您的帮助)。
  • @MrFlick,感谢您编辑我的原始帖子并正确格式化。 (我会学会这样做)。

标签: r web screen-scraping scraper


【解决方案1】:

这是提取该信息的一种方法

str1<-"Simplify the polynomial by combining like terms. <img src=\"/flx/math/inline/3x%2B12-11x%2B14\" class=\"x-math\" alt=\"3x+12-11x+14\" />"

library(scrapeR)    
y<-scrape(object="str1")[[1]] #just get the first result

pretext <- sapply(xpathSApply(y, "//img/preceding::text()"), xmlValue)
alttext <- xpathSApply(y, "//img/@alt")

paste(pretext, alttext)
#[1] "Simplify the polynomial by combining like terms.  3x+12-11x+14"

scrape() 将返回类似 HTML/XML 的文档,您可以使用类似 xpathSApply 的函数来查找节点并提取值。

【讨论】:

  • 非常感谢。有用。现在我要弄清楚它为什么会起作用! (感谢您让我朝着正确的方向前进)
  • 找到了一个关于使用 R 进行网页抓取的好教程。只是将其发布以供将来使用。 files.meetup.com/1503964/2010-06-24_WebScrapeIntro.pdf
猜你喜欢
  • 1970-01-01
  • 2021-06-04
  • 2020-09-28
  • 1970-01-01
  • 2021-07-17
  • 2021-10-28
  • 2020-04-19
  • 2018-09-29
  • 1970-01-01
相关资源
最近更新 更多