【发布时间】:2018-02-17 03:08:23
【问题描述】:
背景 我目前正在使用 rvest 从 R 中的一些网站上抓取产品信息。这适用于除一个网站之外的所有网站,其中内容似乎是通过 angularJS (?) 动态加载的,因此无法迭代加载,例如通过 URL 参数(就像我对其他网站所做的那样)。具体网址如下:
http://www.hornbach.de/shop/Badarmaturen/Waschtischarmaturen/S3584/artikelliste.html
请记住,我在我的机器上没有管理员权限,只能实施不需要或仅需要一次性授予管理员权限的解决方案
所需的输出 最后,R 中的表格包含产品信息(例如标签、价格、评级)=> 不过,在这个问题中,我完全需要帮助来动态加载和存储网站;我可以自己处理 R 中的后处理。 如果你能把我推向正确的方向,那就太好了;也许我下面列出的方法之一是正确的,但我似乎无法将它们转移到所述网站。
目前的做法 我发现 phantomJS 作为一个无头浏览器,afaik 应该能够处理这个问题。我对 Java Script 几乎一无所知,而且语法与我更习惯的语言(R、Matlab、SQL)有很大不同(至少对我而言),我真的很难实现在其他地方建议的可能适用的方法我的代码。 基于this example(非常感谢),我设法使用以下代码从显示的第一个页面中至少检索到信息:
R:
require(rvest)
## change Phantom.js scrape file
url <- 'http://www.hornbach.de/shop/Badarmaturen/Waschtischarmaturen/S3584/artikelliste.html'
lines <- lines <- readLines("scrape_final.js")
lines[1] <- paste0("var url ='", url ,"';")
writeLines(lines, "scrape_final.js")
## Download website
system("phantomjs scrape_final.js")
### use Rvest to scrape the downloaded website.
web <- read_html("1.html")
content <- html_nodes(web, 'div.paging-indicator')# %>% html_attr('href')
content <- html_text(content) %>% as.data.frame()
以及对应的 PhantomJS 脚本:
var url ='http://www.hornbach.de/shop/Badarmaturen/Waschtischarmaturen/S3584/artikelliste.html';
var page = new WebPage()
var fs = require('fs');
page.open(url, function (status) {
just_wait();
});
function just_wait() {
setTimeout(function() {
fs.write('1.html', page.content, 'w');
phantom.exit();
}, 2500);
}
什么不起作用 // 研究 虽然此代码从第一页检索信息,但我确实需要遍历所有 x 个产品页面。我尝试使用以下示例扩展上面的代码:
Unable to scrape multiple pages using phantomjs in r
[使用 phantomjs 抓取动态加载页面][3]
[Web抓取在R中动态加载数据][4]
这些例子让我想到了这个想法
- 点击“下一页”按钮
-
或者以某种方式注入正确的分页值
- 点击“下一页”按钮
如下所示
var url ='http://www.hornbach.de/shop/Badarmaturen/Waschtischarmaturen/S3584/artikelliste.html';
var page = require('webpage').create();
var fs = require('fs');
page.open(url, function (status) {
age.open(url, function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
$("paging-btn right").click();
just_wait();
});
phantom.exit()
});
});
function just_wait() {
setTimeout(function() {
fs.write('1.html', page.content, 'w');
phantom.exit();
}, 2500);
}
但由于语法不佳以及其他原因,这对我没有任何帮助。 不幸的是,从 R 调用这个脚本不会产生错误,它只运行了很长时间,所以我必须退出它(而工作脚本只需要几秒钟)。
我使用了 firefox 的小工具检查器来检索按钮名称,但这也可能是错误的:
<a class="paging-btn right rel="next" ng-click="goToNextPage()"
ng-hide="articleData.pageNumber == articleData.pageCount"
href="javascript:void(0);">right</a>
- 加载时更改分页参数
我尝试在此处处理给定的示例 Passing variable into page.evaluate - PhantomJS
但也只是得到了一个从未以 R 结尾的脚本
补充说明 看起来我只能发布两个链接,所以很遗憾,我无法链接我研究和测试过的所有来源。
我很清楚这是一个庞大而混乱的信息,如果您能帮助我改进/更好地组织我的问题,请告诉我。我会尽力响应并为您提供任何您需要的帮助。
【问题讨论】:
标签: jquery angularjs web-scraping phantomjs rvest