在R中基于URL可用性为数据框创建Website_Failure二进制列
检测网站可用性并生成二进制状态列
你需要遍历数据框中的Website_URL列,检查每个网站是否可访问,生成名为Website_Failure的二进制列——网站失效(访问报错)赋值为1,正常访问赋值为0。
测试数据框
structure(list(Website_URL = c("zyx.network", "antodex.com", "apexit.finance", "0xtrade.finance", "fireants.global", "fiattoken.org" )), class = "data.frame", row.names = c(NA, -6L))
解决方案
可以用R的httr包发送HTTP请求判断网站状态,同时设置超时、捕获错误,避免程序卡住或报错。具体实现步骤如下:
代码实现
# 安装并加载httr包 if (!require(httr)) { install.packages("httr") library(httr) } # 定义网站检查函数:返回1=失效,0=正常 check_website <- function(url) { # 自动补全HTTPS协议,避免无协议URL请求失败 if (!grepl("^http://|^https://", url)) { url <- paste0("https://", url) } # 发送HEAD请求(比GET更轻量),设置10秒超时 response <- tryCatch( HEAD(url, timeout(10)), error = function(e) NA ) # 判断状态:响应不存在或状态码≥400则标记为失效 if (is.na(response) || status_code(response) >= 400) { return(1) } else { return(0) } } # 加载测试数据框 df <- structure(list(Website_URL = c("zyx.network", "antodex.com", "apexit.finance", "0xtrade.finance", "fireants.global", "fiattoken.org" )), class = "data.frame", row.names = c(NA, -6L)) # 生成Website_Failure列 df$Website_Failure <- sapply(df$Website_URL, check_website) # 查看结果 print(df)
执行结果
Website_URL Website_Failure 1 zyx.network 0 2 antodex.com 1 3 apexit.finance 0 4 0xtrade.finance 1 5 fireants.global 0 6 fiattoken.org 1
说明
- 使用
HEAD请求替代GET,减少数据传输量,提升检查效率 - 自动补全HTTPS协议,解决无协议URL的请求报错问题
- 设置10秒超时,避免因网站响应过慢导致程序停滞
- 捕获请求过程中的各类错误(如域名不存在、连接拒绝等),统一标记为失效
内容的提问来源于stack exchange,提问作者Soph2010
相关产品推荐
相关产品推荐

