【问题标题】:how to do for loop on that code in R. I want to do web scraping [closed]如何在 R 中对该代码执行 for 循环。我想做网页抓取 [关闭]
【发布时间】:2014-10-08 02:22:36
【问题描述】:

我有很多 url 地址,我想在下面应用这两行代码:

a <- htmlTreeParse("url address",useInternal=T,encoding='UTF-8') 
d <- xpathSApply(a,"//div[@class='text']",xmlValue) 

我该怎么做?

我试过了:

urls <- read.table("file.txt") #txt file with all url's

for(i in 1:200){        
  a <- 1:200        
  c <- 1:200     
  d <- 1:200

  a[i]<-as.character(urls[i,])    
  c[i] <- htmlTreeParse(a[i],useInternal=T,encoding='UTF-8')        
  d[i] <- xpathSApply(c[i],"//div[@class='text']",xmlValue)   
}

我在上面代码中的问题是xpathSApply 函数使用类XMLInternalDocument 的对象,所以c[i] 应该属于该类。但我不知道我该怎么做

【问题讨论】:

  • 所有这些 url 从哪里填充?
  • 我有一个包含所有内容的 txt 文件

标签: r for-loop web-scraping


【解决方案1】:

试试:

urls<-read.table("file.txt") #txt file with all url's

a <- c()
c <- c()
d <- c()

for(i in 1:200){
a[i]<- as.character(urls[i,])
c   <- htmlTreeParse(a[i],useInternal=T,encoding='UTF-8')
d[i]<- xpathSApply(c,"//div[@class='text']",xmlValue)
}

【讨论】:

  • 我收到以下错误消息:“c[i] 中的错误
  • htmlTreeParse(a[i],useInternal=T,encoding='UTF-8') 对于 i=1 的输出是什么?
  • 我的问题是我无法将应用函数htmlTreeParse a [i] = T useInternal, encoding = 'UTF-8')的返回对象存储到将在xpathSApply函数中使用的“HTMLInternalDocument”“XMLInternalDocument”“XMLAbstractDocument”类的对象中跨度>
  • c&lt;-htmlTreeParse(a[1],useInternal=T,encoding='UTF-8') 这行得通吗?告诉我c中包含的值。
  • 当我写信时:a[1]&lt;- as.character(urls[1,]); c[1] &lt;- htmlTreeParse(a[1],useInternal=T,encoding='UTF-8') 我得到了同样的错误信息。但是当我写的时候:a[1]&lt;- as.character(urls[1,]); htmlTreeParse(a[1],useInternal=T,encoding='UTF-8') 我得到了一个类“HTMLInternalDocument”“XMLInternalDocument”“XMLAbstractDocument”的对象。
猜你喜欢
  • 2021-07-27
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 2022-01-24
  • 1970-01-01
  • 2017-08-06
相关资源
最近更新 更多