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

作者: celestialgod (天)   2016-07-27 19:11:52
※ 引述《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>
剩下再做一些資料整理就好了,他有一些跨欄的表格

Links booklink

Contact Us: admin [ a t ] ucptt.com