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

标签 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')

最佳答案

您的尝试就快完成了。请注意,您可以扩展 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"

关于javascript - 使用 R 从 Javascript 检索文本(html 节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108469/

相关文章:

javascript - DOM GetElementsByTagName 问题

javascript - 在 <head> 之前加载屏幕

javascript - 在 php 中发送不同的列而不是 this.value 到 javascript 函数(查询)

r - r 中的手动 PIL 逊相关

xml - 使用ImportXML和XPath从XML提取数据

javascript - 如何将脚本标记应用于特定元素,而不应用于其他元素

r - 在 R 中使用 dplyr::if_else 条件创建新列

r - 如何使用 R 中的热图绘制混淆矩阵?

firefox - 使用 Firefox WebDriver 时选择所有具有文本的节点的 Xpath 表达式是什么?

php - 使用 XPATH 节点从产品中获取数据并将其插入表中