11

我使用 XML 包从这个 url获取链接。

# Parse HTML URL
v1WebParse <- htmlParse(v1URL)
# Read links and and get the quotes of the companies from the href
t1Links <- data.frame(xpathSApply(v1WebParse, '//a', xmlGetAttr, 'href'))

虽然这种方法非常有效,但我使用过rvest并且在解析网络时似乎比XML. 我试过了html_nodeshtml_attrs但我无法让它工作。

4

4 回答 4

16

尽管有我的评论,但您可以使用rvest. 请注意,我们需要使用htmlParsefirst 读取页面,因为该站点已text/plain为该文件设置了内容类型,并且会让人rvest头晕目眩。

library(rvest)
library(XML)

pg <- htmlParse("http://www.bvl.com.pe/includes/empresas_todas.dat")
pg %>% html_nodes("a") %>% html_attr("href")

##   [1] "/inf_corporativa71050_JAIME1CP1A.html" "/inf_corporativa10400_INTEGRC1.html"  
##   [3] "/inf_corporativa66100_ACESEGC1.html"   "/inf_corporativa71300_ADCOMEC1.html"  
## ...
## [273] "/inf_corporativa64801_VOLCAAC1.html"   "/inf_corporativa58501_YURABC11.html"  
## [275] "/inf_corporativa98959_ZNC.html"  

这进一步说明了包rvestXML基础。

更新

rvest::read_html()现在可以直接处理:

pg <- read_html("http://www.bvl.com.pe/includes/empresas_todas.dat")
于 2014-12-04T17:25:30.300 回答
4

我知道您正在寻找rvest答案,但这是使用该 XML软件包的另一种方法,它可能比您正在做的更有效。

你见过里面的getLinks()功能example(htmlParse)吗?我使用示例中的这个修改版本来获取href链接。它是一个处理函数,因此我们可以在读取值时收集它们,从而节省内存并提高效率。

links <- function(URL) 
{
    getLinks <- function() {
        links <- character()
        list(a = function(node, ...) {
                links <<- c(links, xmlGetAttr(node, "href"))
                node
             },
             links = function() links)
        }
    h1 <- getLinks()
    htmlTreeParse(URL, handlers = h1)
    h1$links()
}

links("http://www.bvl.com.pe/includes/empresas_todas.dat")
#  [1] "/inf_corporativa71050_JAIME1CP1A.html"
#  [2] "/inf_corporativa10400_INTEGRC1.html"  
#  [3] "/inf_corporativa66100_ACESEGC1.html"  
#  [4] "/inf_corporativa71300_ADCOMEC1.html"  
#  [5] "/inf_corporativa10250_HABITAC1.html"  
#  [6] "/inf_corporativa77900_PARAMOC1.html"  
#  [7] "/inf_corporativa77935_PUCALAC1.html"  
#  [8] "/inf_corporativa77600_LAREDOC1.html"  
#  [9] "/inf_corporativa21000_AIBC1.html"     
#  ...
#  ...
于 2014-12-04T15:29:59.420 回答
2
# Option 1
library(RCurl)
getHTMLLinks('http://www.bvl.com.pe/includes/empresas_todas.dat')

# Option 2
library(rvest)
library(pipeR) # %>>% will be faster than %>%
html("http://www.bvl.com.pe/includes/empresas_todas.dat")%>>% html_nodes("a") %>>% html_attr("href")
于 2015-01-29T19:26:23.430 回答
0

理查德的回答适用于 HTTP 页面,但不适用于我需要的 HTTPS 页面(维基百科)。我替换了 RCurl 的 getURL 函数如下:

library(RCurl)

links <- function(URL) 
{
  getLinks <- function() {
    links <- character()
    list(a = function(node, ...) {
      links <<- c(links, xmlGetAttr(node, "href"))
      node
    },
    links = function() links)
  }
  h1 <- getLinks()
  xData <- getURL(URL)
   htmlTreeParse(xData, handlers = h1)
  h1$links()
}
于 2016-04-26T20:43:58.763 回答