現在我已經找到了解決辦法 - 我注意到的價值花了一些時間來加載,所以我列入PhnatomJS腳本有點超時。現在,它的工作原理在我的機器上有下列R-代碼:
setwd("path/to/phantomjs/bin")
system('phantomjs readexample.js') # call PhantomJS script (stored in phantomjs/bin)
totalCiteCount <- "rendered_page.html" %>% # "rendered_page.html" is created by PhantomJS
read_html() %>%
html_nodes("#totalCiteCount") %>%
html_text()
## totalCiteCount
## [1] "52018"
相應PhantomJS腳本文件「readexample.js」看起來像下面(榮譽給https://www.r-bloggers.com/web-scraping-javascript-rendered-sites/):
var webPage = require('webpage');
var url ='https://www.scopus.com/authid/detail.uri?authorId=7006040753';
var fs = require('fs');
var page = webPage.create();
var system = require('system');
page.settings.userAgent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
page.open(url, function (status) {
setTimeout(function() {
fs.write('rendered_page.html', page.content, 'w');
phantom.exit();
}, 2500);
});
代碼投在R中出現錯誤,但至少該值是正確的。
> system('phantomjs readexample.js') TypeError: undefined is not a constructor (evaluating 'mutation.addedNodes.forEach')
https://www.scopus.com/gzip_N1846232499/bundles/SiteCatalystTop.js:73 :0 in forEach https://www.scopus.com/gzip_N1846232499/bundles/SiteCatalystTop.js:73 ReferenceError: Can't find variable: SDM
https://www.scopus.com/gzip_N1729184664/bundles/AuthorProfileTop.js:73 in sendIndex https://www.scopus.com/gzip_N1729184664/bundles/AuthorProfileTop.js:67 in loadEvents
使用PhantomJS是相當方便的,因爲你沒有安裝任何東西(如果你沒有你的機器上的管理員權限,從而也適用)。只需download .zip文件並將其解壓縮到任何文件夾。之後在R(setwd()
)中將工作目錄設置爲「phantomjs/bin」文件夾,它工作。
還可以改變PhantomJS scripte(迭代如果需要的話)中的R例如在循環中將不同的URL傳遞給腳本。例如:
for (i in 1:n_urls) {
url_var <- urls[i] # assuming you have created a var "urls" with multiple URLs before
lines <- readLines("readexample.js")
lines[2] <- paste0("var url ='", url_var ,"';") # exchange code line with new URL
writeLines(lines, "readexample.js") # new url is stored in the PhantomJS script
system('phantomjs readexample.js')
# <any code> #
}
希望這會帶給你更進一步嗎?
活像乍一看速戰速決,但是這個值似乎是動態加載(如果你看看源代碼,你會發現數量不會出現在任何地方),這意味着你首先必須使網站使用例如PhantomJS或RSelenium並隨後下載/處理網站rvest – TomS
我剛剛嘗試過PhantomJS,並且由於頁面處理似乎被阻止而在這裏也遇到問題。所以寧願使用RSelenium(不幸的是我對此沒有任何認識),或者可能與文檔的數量有關,而不是可以被簡化的總引用數量(並且更有意義,因爲引用多少文檔更重要,不是每個文檔的頻率) – TomS
您好湯姆,感謝您的評論......你是什麼意思,「如果你看看源代碼,你會注意到這個數字沒有出現在任何地方」。實際上,在html源代碼中,我發現''還有' 51971''。 – Guglielmo