1. ?read_html(url, encoding = "") 下載html頁面, url為網址,encoding為網址編碼
2. ?html_form(x) 解析網頁的表單信息
eg: box_office <- read_html("http://www.boxofficemojo.com/movies/?id=ateam.htm")
? ? ? box_office %>% html_node("form") %>% html_form()
3. ?html_nodes(x, css, xpath)
? ? ?html_node(x, css, xpath) ?從html文件中選取標簽
? ? ?CSS 選擇器參考手冊 http://www.w3school.com.cn/cssref/css_selectors.asp
4. html_text(x) 讀取文本內容
5. html_attr(x)讀取屬性值
library(rvest) #導入rvest包
num <- seq(0, 225, by = 25) #構建0, 25,50,...,225的向量
info <- c()#初始化向量,用于存儲書籍信息
bookname <- c()#初始化向量,用于存儲書名
info1 <- c()#初始化向量,用于存儲循環采集到某一頁的書籍信息
bookname1 <- c()#初始化向量,用于存儲循環采集到某一頁得書名
for(i in num){
url <- paste0("https://book.douban.com/top250?start=",i) ?#構建采集網址
webpage <- read_html(url) #下載網頁內容
info1 <- html_nodes(webpage, "p[class='pl']") %>% html_text() #讀取書籍信息
bookname1 <- html_nodes(webpage, "div[class='pl2'] a") %>% html_text() #讀取書名
info <- c(info, info1) #新采集到的書籍信息,追加到info向量后
bookname <- c(bookname, bookname1) #新采集到的書名信息,追加到bookname向量后
}
topbook250 <- data.frame(bookname, info) #構建數據框