【问题标题】:How write code to web crawling and scraping in R如何在 R 中编写代码以进行网络爬取和抓取
【发布时间】:2014-08-25 22:48:34
【问题描述】:

我正在尝试编写将转到每个页面并从那里获取信息的代码。 网址 http://www.wikiart.org/en/claude-monet/mode/all-paintings-by-alphabet

我有输出所有href的代码。但它不起作用。

library(XML)
library(RCurl)
library(stringr)
tagrecode <- readHTMLTable ("http://www.wikiart.org/en/claude-monet/mode/all-            paintings-by-alphabet")
tabla <- as.data.frame(tagrecode)
str(tabla)
names (tabla) <- c("name", "desc", "cat", "updated")
str(tabla)
res <- htmlParse ("http://www.wikiart.org/en/claude-monet/mode/all-paintings-by- alphabet")
enlaces <- getNodeSet (res, "//p[@class='pb5']/a/@href")
enlaces <- unlist(lapply(enlaces, as.character))
tabla$enlace <- paste("http://www.wikiart.org/en/claude-monet/mode/all-paintings-by- alphabet")
str(tabla)
lisurl <- tabla$enlace

fu1 <- function(url){
print(url)
pas1 <- htmlParse(url, useInternalNodes=T)

pas2 <- xpathSApply(pas1, "//p[@class='pb5']/a/@href")
}
urldef <- lapply(lisurl,fu1)

在我得到这个页面上所有图片的url列表后,我想去第二-第三-...-23页收集所有图片的url。

下一步 - 废弃每张图片的信息。 我有一个工作代码,我需要在一个通用代码中构建它。

library(XML)
url = "http://www.wikiart.org/en/claude-monet/camille-and-jean-monet-in-the-garden-at-argenteuil"
doc = htmlTreeParse(url, useInternalNodes=T)
pictureName <- xpathSApply(doc,"//h1[@itemprop='name']", xmlValue)
date <- xpathSApply(doc, "//span[@itemprop='dateCreated']", xmlValue)
author <- xpathSApply(doc, "//a[@itemprop='author']", xmlValue)
style <- xpathSApply(doc, "//span[@itemprop='style']", xmlValue)
genre <- xpathSApply(doc, "//span[@itemprop='genre']", xmlValue)

pictureName
date
author
style
genre

我们将不胜感激任何建议!

【问题讨论】:

    标签: r web screen-scraping web-crawler


    【解决方案1】:

    这似乎有效。

    library(XML)
    library(httr)
    url <- "http://www.wikiart.org/en/claude-monet/mode/all-paintings-by-alphabet/"
    hrefs <- list()
    for (i in 1:23) {
      response <- GET(paste0(url,i))
      doc      <- content(response,type="text/html")
      hrefs    <- c(hrefs,doc["//p[@class='pb5']/a/@href"])
    }
    url      <- "http://www.wikiart.org"
    xPath    <- c(pictureName = "//h1[@itemprop='name']",
                  date        = "//span[@itemprop='dateCreated']",
                  author      = "//a[@itemprop='author']",
                  style       = "//span[@itemprop='style']",
                  genre       = "//span[@itemprop='genre']")
    get.picture <- function(href) {
      response <- GET(paste0(url,href))
      doc      <- content(response,type="text/html")
      info     <- sapply(xPath,function(xp)ifelse(length(doc[xp])==0,NA,xmlValue(doc[xp][[1]])))
    }
    pictures <- do.call(rbind,lapply(hrefs,get.picture))
    head(pictures)
    #      pictureName                           date     author         style           genre           
    # [1,] "A Corner of the Garden at Montgeron" "1877"   "Claude Monet" "Impressionism" "landscape"     
    # [2,] "A Corner of the Studio"              "1861"   "Claude Monet" "Realism"       "self-portrait" 
    # [3,] "A Farmyard in Normandy"              "c.1863" "Claude Monet" "Realism"       "landscape"     
    # [4,] "A Windmill near Zaandam"             NA       "Claude Monet" "Impressionism" "landscape"     
    # [5,] "A Woman Reading"                     "1872"   "Claude Monet" "Impressionism" "genre painting"
    # [6,] "Adolphe Monet Reading in the Garden" "1866"   "Claude Monet" "Impressionism" "genre painting"
    

    其实你们已经很亲近了。你的 xPath 很好;一个问题是并非所有图片都包含所有信息(例如,对于某些页面,您尝试访问的节点集是空的) - 请注意“A Windnill nead Zaandam”的日期。所以代码必须处理这种可能性。

    因此,在本例中,第一个循环获取每个页面 (1:23) 的锚标记的 href 属性值,并将这些值组合成一个长度约为 1300 的向量。

    要处理这 1300 个页面中的每一个,并且由于我们必须处理丢失的标签,创建一个包含 xPath 字符串的向量并将该元素逐个应用于每个页面会更直接。这就是函数get.picture(...) 的作用。最后一条语句使用 1300 个 href 中的每一个调用此函数,并使用 do.call(rbind,...) 将结果逐行绑定在一起。

    还请注意,此代码对 HTMLInternalDocument 类的对象使用了更紧凑的索引功能:doc[xpath] 其中xpath 是一个 xPath 字符串。这避免了使用xpathSApply(...),尽管后者会起作用。

    【讨论】:

      【解决方案2】:

      你可以试试Rcrawler package,它是一个并行的网络爬虫,它可以使用 XPath 抓取、存储网页和抓取其内容。

      如果你需要收集所有图片信息使用

      datapattern<-c(
        "//h1/span[@itemprop='name']",
        "//a[@class='artist-name']",
        "//*[@id='headSection']/article/form/div[1]/div/div/div[2]/div[2]/span[2]",
        "//*[@id='headSection']/article/form/div[1]/div/div/div[2]/div[3]/a/span",
        "//*[@id='headSection']/article/form/div[1]/div/div/div[2]/div[4]/a/span"
      )
      
      Rcrawler(Website = "https://www.wikiart.org/", no_cores = 4, no_conn = 4, ExtractPatterns =datapattern )
      

      只过滤掉克劳德·莫奈的照片

      Rcrawler(Website = "https://www.wikiart.org/", no_cores = 4, no_conn = 4, urlregexfilter ="claude-monet/([^/])*", ExtractPatterns =datapattern )
      

      爬虫需要一些时间才能完成,因为它会遍历所有网站链接。但是,您可以随时停止执行。默认情况下,抓取的数据位于名为 DATA 的全局变量中,另一个名为 INDEX 的变量包含所有抓取的 URL。

      如果你需要学习如何构建你的爬虫,请参考这篇论文。R crawler

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 2022-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多