2015-10-27 2 views
-5

Мне нужно создать таблицу в списке R для списка розничных продавцов одежды по странам, используя веб-страницу https://en.wikipedia.org/wiki/Category:Clothing_brands_by_country.Как очистить данные из Википедии с помощью R

Я пробовал смотреть на различные ссылки, но не мог найти ничего, что сработало. Основная потребность прямо сейчас состоит в том, чтобы иметь возможность извлекать ссылки со страницы, а затем принуждать ее открывать и очищать данные от нее.

library(XML) 
library(RCurl) 
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))) 


path<-"https://en.wikipedia.org/wiki/Category:Clothing_brands_by_country" 
webpage <- getURL(path) 
webpage <- readLines(tc <- textConnection(webpage)); close(tc) 
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE, encoding=FALSE) 
+0

не имеют возможности ... Я знаю R для стандартного анализа, а не для скребков. Можете сделать это с Python, но не вариант, к сожалению –

+0

Проверьте пакет rvest и демонстрационную версию. Это может помочь вам дальше. Или просто скопируйте и вставьте информацию. – phiver

+0

Что делает ваш код в настоящее время? – halfer

ответ

1

Приведено в действие, не зная, что HTML является основной проблемой. :

library(XML) 
library(RCurl) 
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem",  package = "RCurl"))) 
path<-"http://en.wikipedia.org/wiki/Category:Clothing_brands_by_country" 
webpage <- getURL(path) 
webpage <- readLines(tc <- textConnection(webpage)); close(tc) 
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE, encoding=FALSE) 
q='//a[@class="CategoryTreeLabel CategoryTreeLabelNs14 CategoryTreeLabelCategory"]' 

a<-xpathSApply(pagetree, q, xmlGetAttr,'href') 
t <- gsub('\\s', '', a,) 
x<-data.frame(t) 
x$pos<-gregexpr(pattern ='of_',x$t) 
x$country<-substr(substr(x$t,x$pos,10000),4,10000) 
x$url<-paste("https://en.wikipedia.org",x$t,sep="") 

chk<-x[1,] 
chk2<-chk$url 
country<-chk$country 
webpage <- getURL(chk2) 
webpage <- readLines(tc <- textConnection(webpage)); close(tc) 
pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE, encoding=FALSE) 
q<-'//div[@class="mw-content-ltr"]//ul/li/a' 
a<-xpathSApply(pagetree, q, xmlGetAttr,'title') 
n<-data.frame(a) 
n$country<-country 
fin<-n 

for (i in 2:25) 
{ 
    chk<-x[i,] 
    chk2<-chk$url 
    country<-chk$country 
    webpage <- getURL(chk2) 
    webpage <- readLines(tc <- textConnection(webpage)); close(tc) 
    pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE, encoding=FALSE) 
    q<-'//div[@class="mw-content-ltr"]//ul/li/a' 
    a<-xpathSApply(pagetree, q, xmlGetAttr,'title') 
    n<-data.frame(a) 
    n$country<-country 
    fin<-rbind(fin,n) 
} 
Смежные вопросы