从地图上从网上抓取PDF文件

时间:2018-08-27 20:41:51

标签: r google-maps pdf web-scraping

我一直在尝试按照此代码下载嵌入在地图中的pdf文件(可以在here上找到原始文件)。每个pdf都引用了巴西的一个自治市(5,570个文件)。

library(XML)
library(RCurl)
url <- "http://simec.mec.gov.br/sase/sase_mapas.php?uf=RJ&tipoinfo=1"
page   <- getURL(url)
parsed <- htmlParse(page)
links  <- xpathSApply(parsed, path="//a", xmlGetAttr, "href")
inds   <- grep("*.pdf", links)
links  <- links[inds]
regex_match <- regexpr("[^/]+$", links, perl=TRUE)
destination <- regmatches(links, regex_match)
for(i in seq_along(links)){
  download.file(links[i], destfile=destination[i])
  Sys.sleep(runif(1, 1, 5))
}

我已经在其他项目中使用过此代码几次,并且有效。对于这种特定情况,不是。实际上,我已经尝试了很多方法来刮擦这些文件,但是对我来说似乎是不可能的。最近,我得到了以下链接。然后可以将uf(州)和muncod(市政代码)组合起来下载文件,但是我不知道如何将其包含在代码中。

  

http://simec.mec.gov.br/sase/sase_mapas.php?uf=MT&muncod=5100102&acao=download

谢谢!

1 个答案:

答案 0 :(得分:0)

devtools::install_github("ropensci/RSelenium")

library(rvest)
library(httr)
library(RSelenium)

# connect to selenium server from within r (REPLACE SERVER ADDRESS)
rem_dr <- remoteDriver(
  remoteServerAddr = "192.168.50.25", port = 4445L, browserName = "firefox"
)

rem_dr$open()

# get the two-digit state codes for brazil by scraping the below webpage
tables <- "https://en.wikipedia.org/wiki/States_of_Brazil" %>%
  read_html() %>%
  html_table(fill = T)
states <- tables[[4]]$Abbreviation

# for each state, we are going to go navigate to the map of that state using
# selenium, then scrape the list of possible municipality codes from the drop
# down menu present in the map
get_munip_codes <- function(state) {
  url <- paste0("http://simec.mec.gov.br/sase/sase_mapas.php?uf=", state)
  rem_dr$navigate(url)
  # have to wait until the drop down menu loads. 8 seconds will be enough time
  # for each state
  Sys.sleep(8)
  src <- rem_dr$getPageSource()

  out <- read_html(src[[1]]) %>%
    html_nodes(xpath = "//select[@id='muncod']/option[boolean(@value)]") %>%
    xml_attrs("value") %>%
    unlist(use.names = F)

  print(state)
  out
}

state_munip <- sapply(
  states, get_munip_codes, USE.NAMES = TRUE, simplify = FALSE
)

# now you can download each pdf. first create a directory for each state, where
# the pdfs for that state will go:
lapply(names(state_munip), function(x) dir.create(file.path("brazil-pdfs", x)))

# ...then loop over each state/municipality code and download the pdf
lapply(
  names(state_munip), function(state) {
    lapply(state_munip[[state]], function(munip) {
      url <- sprintf(
        "http://simec.mec.gov.br/sase/sase_mapas.php?uf=%s&muncod=%s&acao=download",
        state, munip
      )
      file <- file.path("brazil-pdfs", state, paste0(munip, ".pdf"))
      this_one <- paste0("state ", state, ", munip ", munip)
      tryCatch({
        GET(url, write_disk(file, overwrite = TRUE))
        print(paste0(this_one, " downloaded"))
      },
      error = function(e) {
        print(paste0("couldn't download ", this_one))
        try(unlink(file, force = TRUE))
      }
      )
    })
  }
)

STEPS:

  1. 获取Windows计算机的IP地址(请参见https://www.digitalcitizen.life/find-ip-address-windows

  2. 通过运行以下命令启动selenium服务器docker容器: docker run -d -p 4445:4444 selenium/standalone-firefox:2.53.1

  3. 通过运行以下命令启动rocker / tidyverse docker容器: docker run -v `pwd`/brazil-pdfs:/home/rstudio/brazil-pdfs -dp 8787:8787 rocker/tidyverse

  4. 进入您喜欢的浏览器并输入以下地址:http://localhost:8787 ...这将带您进入rstudio服务器的登录屏幕。使用用户名“ rstudio”和密码“ rstudio”登录

  5. 将上面显示的代码复制/粘贴到新的Rstudio .R文档中。将remoteServerAddr的值替换为您在步骤1中找到的IP地址。

  6. 运行代码...这应将pdfs写入容器内并映射到Windows机器的目录“巴西pdfs”(换句话说,pdf会显示在巴西) -pdfs目录也在您的本地计算机上)。请注意,运行代码b / c需要一段时间,其中包含很多pdf。