Re: [問題] 爬蟲新手問題

看板R_Language作者 (天)時間9年前 (2016/07/27 19:11), 9年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《Tampa (光芒)》之銘言: : [問題類型]: : 網頁爬蟲,已找出xpath,但無法製作成data.frame : [軟體熟悉度]: : 中新手 : [問題敘述]: : 網頁爬蟲,想把wiki的球隊資訊爬下來 : [程式範例]: : library(magrittr) : library(rvest) : URLteam <- : "https://zh.wikipedia.org/wiki/%E7%BE%8E%E5%9C%8B%E8%81%B7%E6%A5%AD%E6%A3%92%E7%90%83%E5%A4%A7%E8%81%AF%E7%9B%9F" : #網頁 : xpathTeam <- "//table[@class='navbox wikitable']/tbody/tr/td[1]"#球隊隊名的 : xpath : docTeam <- read_html(URLteam, encoding="UTF-8")#將網頁讀進R : rankTeam<- docTeam %>% : html_nodes(.,xpath = xpathTeam) %>% : html_text %>% : iconv(from = "UTF-8", to = "UTF-8") : stockTmp <- data.frame(team=docTeam) : 以下是我噴錯的error : Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = : stringsAsFactors) : : cannot coerce class "c("xml_document", "xml_node")" to a data.frame : 問題1: 不知道怎麼了解自己xpath有沒有抓對 : 問題2:data.frame是不是有設定錯誤? 1. 看起來沒問題 2. doc_team轉成data.frame?? 應該是rankTeam 如果我寫會這樣寫: library(pipeR) library(rvest) library(httr) library(stringi) library(data.table) Sys.setlocale("LC_ALL", 'C') # for windows URLteam <- paste0("https://zh.wikipedia.org/wiki/%E7%BE%8E%E5%9C%8B", "%E8%81%B7%E6%A5%AD%E6%A3%92%E7%90%83%E5%A4%A7%E8%81%AF%E7%9B%9F") rankTeam <- URLteam %>>% GET %>>% content %>>% html_nodes(xpath = "//table[@class='navbox wikitable']") %>>% html_table(fill = TRUE) %>>% `[[`(1) %>>% data.table %>>% `[`( , lapply(.SD, function(x) stri_conv(x, "UTF-8", "BIG5"))) %>>% (setnames(., stri_conv(names(.), "UTF-8", "BIG5"))) Classes 'data.table' and 'data.frame': 32 obs. of 7 variables: # $ 分區 : chr "美國聯盟" "東區" "波士頓紅襪\nBoston Red Sox" ... # $ 隊伍 : chr NA "巴爾的摩金鶯\nBaltimore Orioles" ... # $ 區域/城市: chr NA "馬里蘭州,巴爾的摩\nMaryland, Baltimore" ... # $ 主場 : chr NA "金鶯公園\nOriole Park At Camden Yard" " ... # $ 坐標 : chr NA ... # $ 成立時間 : chr NA "1894年" NA NA ... # $ 加入?? : chr NA "1901年" NA NA ... # - attr(*, ".internal.selfref")=<externalptr> 剩下再做一些資料整理就好了,他有一些跨欄的表格 -- R資料整理套件系列文: magrittr #1LhSWhpH (R_Language) http://tinyurl.com/j3ql84c data.table #1LhW7Tvj (R_Language) http://tinyurl.com/hr77hrn dplyr(上) #1LhpJCfB (R_Language) http://tinyurl.com/jtg4hau dplyr(下) #1Lhw8b-s (R_Language) tidyr #1Liqls1R (R_Language) http://tinyurl.com/jq3o2g3 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.246.31.11 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1469617915.A.267.html ※ 編輯: celestialgod (111.246.31.11), 07/27/2016 23:44:52
文章代碼(AID): #1Nc9Rx9d (R_Language)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1Nc9Rx9d (R_Language)