我是编程新手,没有网络爬虫的经验。我正在macOS High Sierra(10.13.6)上运行R版本3.6.0。
作为一个研究项目的一部分,我试图从Forbes website抓取2000个观测值的表格并将其保存为R中的数据框。在this video的指导下,我能够提取2,000行表的前十行。我不确定为什么只收集前10行,并且尽管我浏览了许多博客和教程,但似乎找不到解决此问题的方法。
注意:网页表在每第十行(1-10,ad,11-20,ad,...)中都有一个广告横幅。这会提示PhantomJS停止抓取表格吗?
就像我说的那样,我是网络爬虫的新手,对移动部件不太确定。您可以建议或提供的任何见解或资源都将具有很大的意义!
这是我正在使用的代码,它成功提取了前10行,但没有提取全部2,000行:
## Install packages if necessary:
install.packages("rvest")
install.packages("stringr")
install.packages("plyr")
install.packages("dplyr")
install.packages("ggvis")
install.packages("knitr")
## Load them:
library("rvest")
library("stringr")
library("plyr")
library("dplyr")
library("ggvis")
library("knitr")
### At this point I downloaded and moved PhantomJS to my working directory.
## Establish connections
url <- ("https://www.forbes.com/global2000/list/")
connection <- "forbes_list.js"
## Extract content
writeLines(sprintf("var page = require('webpage').create();
page.open('%s',function() {
console.log(page.content); //page source
phantom.exit();
})",url),con = connection)
system_input <- "./phantomjs forbes_list.js>forbes_list.html"
system(system_input)
## Read in html
html <- "forbes_list.html"
pg <- read_html(html)
## Extract Table
table <- pg %>%html_nodes(xpath = '(//*[@id="the_list"])') %>% html_table()
我得到以下结果:
> table
[[1]]
Rank Company Country/Territory Sales
1 NA #1 ICBC China $175.9 B
2 NA #2 JPMorgan Chase United States $132.9 B
3 NA #3 China Construction Bank China $150.3 B
4 NA #4 Agricultural Bank of China China $137.5 B
5 NA #5 Bank of America United States $111.9 B
6 NA #6 Apple United States $261.7 B
7 NA #7 Ping An Insurance Group China $151.8 B
8 NA #8 Bank of China China $126.7 B
9 NA #9 Royal Dutch Shell Netherlands $382.6 B
10 NA #10 Wells Fargo United States $101.5 B
Profits Assets Market Value
1 $45.2 B $4,034.5 B $305.1 B
2 $32.7 B $2,737.2 B $368.5 B
3 $38.8 B $3,382.4 B $225 B
4 $30.9 B $3,293.1 B $197 B
5 $28.5 B $2,377.2 B $287.3 B
6 $59.4 B $373.7 B $961.3 B
7 $16.3 B $1,038.3 B $220.2 B
8 $27.5 B $3,097.6 B $143 B
9 $23.3 B $399.2 B $264.9 B
10 $23.1 B $1,887.8 B $214.7 B
因此效果很好!但是还不够好...:/
再次感谢您的帮助!