这可能是个简单的R问题,但我还在学习。
我有一长串来自环保局的网址,包含在CSV中,链接到特定的排放许可/设施。CSV的每一行都包含一个URL。一些URL转到活动页面,其中包含有关可用设施的信息,而另一些URL(我最终感兴趣识别的URL)转到一个页面,上面写着“未找到NPDES的程序设施--许可证号”。
我想使用R通过这个csv列表的URL,打开每个URL,并返回一个真或假的值,关于URL是好还是坏。一个“坏”URL是基于页面是否返回“没有程序工具找到”文本。理想情况下,返回的真值或假值可以添加到站点URL旁边的列中,这样我就可以轻松地浏览并识别哪些是好链接,哪些不是。
我很感激你对从哪里开始的任何建议!
我能够将它设置为一次使用库(Httr)处理单个链接。
# Bad URL
site1 <- GET("https://iaspub.epa.gov/enviro/fii_query_dtl.disp_program_facility?pgm_sys_id_in=VA0086738&pgm_sys_acrnm_in=NPDES")
contents1 <- content(site1, "text")
any(grepl("No program facility found", contents1))
# [1] TRUE
# Good URL
site2 <- GET("https://iaspub.epa.gov/enviro/fii_query_dtl.disp_program_facility?pgm_sys_id_in=VAG401896&pgm_sys_acrnm_in=NPDES")
contents2 <- content(site2, "text")
any(grepl("No program facility found", contents2))
# [1] FALSE发布于 2019-09-18 21:48:56
以下是您提供的两个链接的解决方案:
library(httr) 我编写了以下几行代码来编写供其他读者使用的数据集(您可以跳过这段代码,从下一段代码开始):
#stackoverflow_question_links<- data.frame("Links"=c("https://iaspub.epa.gov/enviro/fii_query_dtl.disp_program_facility?pgm_sys_id_in=VA0086738&pgm_sys_acrnm_in=NPDES","https://iaspub.epa.gov/enviro/fii_query_dtl.disp_program_facility?pgm_sys_id_in=VAG401896&pgm_sys_acrnm_in=NPDES"))
#write.csv(stackoverflow_question_links, "stackoverflow_question_links.csv")假设您的数据集名为"stackoverflow_question_links.csv",我们开始将其读取到R中:
fileName <- "stackoverflow_question_links.csv"
con <- file(fileName,open="r")
lin <-readLines(con)
save<-NULL #initialize save, to save the links with their status (true/false)
for (i in 2:length(lin)){
site <- GET(lin[i])
contents <- content(site, "text")
save<-rbind(save, data.frame("Link" = lin[i],"Status"=any(grepl("No program facility found", contents))))
}
close(conn)
View(save) #or write.csv(save, "links_status.csv")

发布于 2019-09-19 03:38:16
我们也可以使用rvest来完成这个任务。假设您的数据名为df,并且所有链接都存在于数据的url列中,那么我们可以在dataframe中创建一个新列(text_found),它指示文本('No program facility found')是否在该url上找到。因此,如果在URL中找不到文本,那么它就是一个好的url,反之亦然。
library(rvest)
library(dplyr)
df %>%
mutate(text_found = purrr::map_lgl(url, ~ .x %>% read_html %>%
html_text() %>% grepl('No program facility found', .)),
Good_URL = !text_found)
url text_found Good_URL
1 https://iaspub.epa.gov/enviro...... TRUE FALSE
2 https://iaspub.epa.gov/enviro...... FALSE TRUE数据
df <- data.frame(url = c("https://iaspub.epa.gov/enviro/fii_query_dtl.disp_program_facility?pgm_sys_id_in=VA0086738&pgm_sys_acrnm_in=NPDES",
"https://iaspub.epa.gov/enviro/fii_query_dtl.disp_program_facility?pgm_sys_id_in=VAG401896&pgm_sys_acrnm_in=NPDES"),
stringsAsFactors = FALSE)https://stackoverflow.com/questions/58000716
复制相似问题