代码之家  ›  专栏  ›  技术社区  ›  Nettle

用Rvest删除超链接

  •  1
  • Nettle  · 技术社区  · 8 年前

    my.url <- "https://comptroller.defense.gov/Budget-Materials/Budget2019/"
    my.xpath <- '//*[@id="LiveHTMLWrapper92093"]/div/div'
    
    x <- read_html(my.url) %>% 
      html_node(xpath = my.xpath) 
    
    {xml_node}
    <div style="width: 710px; height: 600px; overflow: auto;">
    [1] <h5 style="text-align: left; background-color: #dbdbe4;"><a name="press" style=" ...
    [2] <p><a href="/Portals/45/Documents/defbudget/fy2019/fy2019_Press_Release.pdf" sty ...
    [3] <p style="margin-top: 1px; margin-bottom: 0px;"><strong><span style="font-family ...
    [4] <p style="margin-top: 1px; margin-bottom: 0px;"><strong><span style="font-family ...
    [5] <p><strong>\n- <a href="https://www.defense.gov/News/Transcripts/Transcript-View ...
    [6] <h5 style="text-align: left; background-color: #dbdbe4;"><a name="summary" style ...
    [7] <div style="height: 50px;">\n<a href="/Portals/45/Documents/defbudget/fy2019/FY2 ...
    [8] <strong><strong>\n<b><strong>\n<b>\n<strong>\n</strong>\n<strong>\n</strong>\n<s ...
    

    理想情况下,我希望输出一个数据框,其中一列包含文本,另一列包含关联的href。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexandre georges    7 年前

    这里有一个解决方案:

    my.url <- "https://comptroller.defense.gov/Budget-Materials/Budget2019/"
    my.xpath <- '//*[@id="dnn_ctr92093_ContentPane"]'
    
    x <- read_html(my.url) %>% 
      html_node(xpath = my.xpath) %>% html_nodes("a") %>% html_text()
    
    y <- read_html(my.url) %>% 
      html_node(xpath = my.xpath) %>% html_nodes("a") %>% html_attr("href") 
    
    y <- ifelse(grepl(pattern = "/Portals/",y), paste0("https://comptroller.defense.gov",y),y)
    
    df <- as.data.frame(cbind(x,y))