【问题标题】:Retrieving text (html node) from Javascript using R使用 R 从 Javascript 中检索文本(html 节点)
【发布时间】:2017-09-08 04:08:10
【问题描述】:

我正在尝试从 “我在很小的时候就理解...宇宙的精神。” 和作者的名字 “Alice Walker” 从以下 Javascript 代码:

<div id="qpos_4_3" class="m-brick grid-item boxy bqQt" style="position: absolute; left: 0px; top: 33815px;">

 <div class="">

  <a href="/quotes/quotes/a/alicewalke625815.html?src=t_age" class="b-qt 
  qt_625815 oncl_q" title="view quote">I understood at a very early age that 
  in nature, I felt everything I should feel in church but never did. 
  Walking in the woods, I felt in touch with the universe and with the 
  spirit of the universe.

  </a>

  <a href="/quotes/authors/a/alice_walker.html" class="bq-aut qa_625815 
  oncl_a" title="view author">Alice Walker</a>

  </div>

  <div class="kw-box">

   <a href="/quotes/topics/topic_nature.html" class="oncl_k" data-
   idx="0">Nature</a>,

  </div>

我使用了 chrome 的开发者工具栏来获取 xpath。以下代码旨在提取报价,但它输出character(0)。我做错了什么?

link <-  "https://www.brainyquote.com/quotes/topics/topic_age.html"
quote <- read_html(link)

quote %>%
  html_nodes(xpath = '//*[@id="qpos_4_3"]/div[1]/a[1]') %>% 
  html_attr('view quote')

【问题讨论】:

  • “您不得通过使用机器人、蜘蛛、爬虫、网络爬虫、索引代理或其他自动化设备访问、使用或复制本网站的任何部分或其内容,或机制。您同意不删除或修改任何版权声明或商标图例、作者署名或放置或包含在任何网站内容中的其他声明。除非我们以书面形式明确授权,否则您在任何情况下都不会复制、重新分发、复制、复制、修改、分发……” 最佳阅读项目 5 here
  • 仅供个人使用和练习创建机器人,但感谢您指出这一点。我会非常小心的。

标签: javascript r xpath web-scraping


【解决方案1】:

你的尝试快到了。请注意,您可以扩展您的 XPath 表达式以包含您试图用html_attr 隔离的title,但您确实想要xml_contents。我添加 magrittr 只是为了管道和可读性,否则不需要...并且我已经将结果强制转换为字符,假设您将进一步使用它们。

get_contents <- function(link, id, title) {

  require(xml2)
  require(magrittr)

  xpath <- paste0(".//div[@id='", id, "']//a[@title='", title, "']")

  read_html(link) %>%
    xml_find_first(xpath) %>%
    xml_contents() %>%
    as.character()

}

link <-  "https://www.brainyquote.com/quotes/topics/topic_age.html"
id <- "qpos_1_10"

quote <- get_contents(link, id, "view quote")

# [1] "In our age there is no such thing as 'keeping out of politics.' All
# issues are political issues, and politics itself is a mass of lies,
# evasions, folly, hatred and schizophrenia."

author <- get_contents(link, id, "view author")

# [1] "George Orwell"

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2013-05-15
    • 2013-09-03
    相关资源
    最近更新 更多