我正在尝试检索引用“我在很小的时候就明白了……宇宙的精神。”和作者的名字“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/