我正在尝试使用 Chrome 中的 RSelenium 从本地在线报纸上抓取或获取 Disqus 评论的文本,但我发现这对我的能力来说有点困难。我搜索了很多地方,但没有找到正确的信息,或者我使用了错误的搜索词(很可能)。
到目前为止,我已经设法从页面中获取“正常”的 html,但无法确定正确的类、css 选择器或 id 来获取 Disqus 评论。我也试过 Selectorgadget 但这只指向 #dsq-app2
它一次选择整个 Disqus 区域,不允许选择该区域的较小部分。我使用 elems <- mybrowser$findElement(using = "id", "dsq-app2")
对 RSelenium 进行了同样的尝试“环境”存储在 elems
中.然后我试图在 elems
中找到子元素但一无所获。
通过开发人员工具查看页面,我可以看到有趣的内容在名为 #dsq-app2
的 iframe 中。并设法通过 elems$getPageSource()
提取了所有来源使用 elems$switchToFrame("dsq-app2")
切换到框架后.这会将所有 html 输出为一个大的“脏” block ,并且没有搜索 <p>
中保存的所需内容。标签和其他感兴趣的元素,例如 data-role="username"
中的海报用户名和其他人,我似乎没有找到正确的前进方向。
我也尝试过使用给出的建议 here但是 Disqus 的设置有点不同。我正在尝试的页面之一是 this在名为 conversation
的部分中包含大部分评论区域和大量其他 ID,例如 posts
和带有 id=post-list
的无序列表最终带有我需要抓取的评论。
我们非常欢迎任何想法或帮助提示,并表示感谢。
最佳答案
经过大量的测试和实验,我成功了。我不知道它是否是最干净或最漂亮的解决方案,但它确实有效。希望其他人会发现它有用。基本上我所做的就是找到只指向评论的 url。这是在“dsq-app2”iframe
中找到的,是一个名为src
的属性
。起初我也切换到 iframe,但发现没有它也能工作。
remDr$navigate("toTheRequiredPage")
elemsource <- remDr$findElement(using = "id", value = "dsq-app2")
src <- elemsource$getElementAttribute("src") # find the src attribute within the iframe`
remDr$navigate(src[[1]]) # navigate to the src url
# find the posts from the new page
elem <- remDr$findElement(using = "id", value = "posts")
elem.posts <- elem$findChildElements(using = "id", value = "post-list")
elem.msgs <- elem.posts[[1]]$findChildElements(using = "class name", value = "post-message")
length(elem.msgs)
msgtext <- elem.msgs[[1]]$getElementText() # find first post's text
msgtext # print message
更新:我发现如果我使用 remDr$switchToFrame("dsq-app2")
我不需要像我上面解释的那样使用 src
url .所以实际上有两种抓取方式;
- 使用
switchToFrame("nameOfFrame")
或 - 使用我之前的解决方案,即使用来自 iframe 的
src
URL
希望这能让它更清楚。
关于html - 用于 Disqus 评论的 RSelenium 抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38315485/