【问题标题】:R - Scrape multiple url and wirte each data url in different excel data sheetsR - 抓取多个 url 并将每个数据 url 写入不同的 excel 数据表中
【发布时间】:2019-08-27 02:42:42
【问题描述】:

我正在尝试抓取不同的 URL 并将数据写入同一个 Excel 文件中,但每个 URL 都在一个页面中。

我的代码是这样的:

#install.packages("rvest")

library(XLConnect)
library(rvest)
{
 for(i in c("2086","2167","2204")) {
   url<-paste0("https://www.silversanz.com/producto/",i,)

}
 dades<-read_html(url)

 nom<-dades %>% html_nodes("h1.title") %>% html_text() %>% trimws()
 preu<-dades %>% html_nodes("p.price--current") %>% html_text() %>% trimws()

 info<-as.data.frame(cbind(nom,preu))

 writeWorksheetToFile(file="C:/xxx.xxx.xlsx",
                   data=info,
                   sheet= "test",
                   clearSheets=TRUE
 )
}

我有两个问题:

  • 此代码不起作用 ->

     for(i in c("2086","2167","2204")) {
     url<-paste0("https://www.silversanz.com/producto/",i,)
    
  • 我不知道每个url怎么写一张

提前致谢:-)

【问题讨论】:

    标签: r lapply rvest scrape


    【解决方案1】:

    您以错误的方式使用了括号。您编写的for-loop 遍历数字并将最后一个保存在url 中。您的 for-loop 应该包含您的所有代码:

    library(XLConnect)
    library(rvest)
    
    for(i in c("2086","2167","2204")) {
    
       url<-paste0("https://www.silversanz.com/producto/",i)
    
       dades<-read_html(url)
    
       nom<-dades %>% html_nodes("h1.title") %>% html_text() %>% trimws()
       preu<-dades %>% html_nodes("p.price--current") %>% html_text() %>% trimws()
    
       info<-as.data.frame(cbind(nom,preu))
    
       writeWorksheetToFile(file="C:/xxx.xxx.xlsx",
                         data=info,
                         sheet= i,
                         clearSheets=TRUE)
    }
    

    至于工作表,既然所有内容都在循环中,只需使用 i 作为工作表名称,以便每个 url 有一个工作表。

    【讨论】:

    • 是的,成功了!!非常感谢,LyzanderR :-)
    • 乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多