使用R从Javascript中检索文本(html节点)

时间:2017-09-08 04:08:11

标签: javascript r xpath web-scraping

我正在尝试检索引用"我很早就明白了......宇宙的精神。" 和作者的名字" 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')

1 个答案:

答案 0 :(得分:2)

你的尝试几乎就在那里。请注意,您可以扩展XPath表达式以包含您尝试与title隔离的html_attr,但您确实需要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"