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