【问题标题】:Scraping Hyperlinks with Rvest使用 Rvest 抓取超链接
【发布时间】:2019-01-19 13:39:34
【问题描述】:

我想使用 rvest 从页面中抓取文本和超链接(.xlsx 和 .pdf 文件)。我不是很擅长这个,所以很难判断我是在处理一个复杂的网页,还是只是在犯新手错误。到目前为止我的代码:

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。

【问题讨论】:

    标签: r dplyr rvest


    【解决方案1】:

    这里有一个解决方案:

    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))
    

    【讨论】:

    • 你这一天做了一件好事!由于我在防火墙后面,所以我必须先使用download.file(my.url, destfile = "scrapedpage.html", quiet=TRUE) 下载文件,否则会出现超时错误。
    猜你喜欢
    • 1970-01-01
    • 2021-03-31
    • 2017-09-13
    • 2021-09-04
    • 2015-11-02
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多