You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中如何检查URL的robots.txt是否存在并获取状态码

如何判断robots.txt是否存在并获取状态码?

嘿,我懂你的困扰——urllib.robotparser确实是解析robots.txt的实用工具,但它把请求细节都封装起来了,没法直接拿到响应状态码或者判断文件是否存在。不过我们可以换个思路:先手动发送请求检查robots.txt的状态,再决定要不要用robotparser来解析它。

解决方案步骤:

  • 先用urllib.request发送HEAD请求(比GET更高效,只返回响应头,不用下载文件内容)获取状态码
  • 根据状态码判断文件是否存在(比如200代表存在,404代表不存在)
  • 如果文件存在,再用robotparser进行后续解析

修改后的完整代码:

from urllib import parse
from urllib import request
from urllib import robotparser

def get_robots_status_and_parser(url_base):
    # 拼接robots.txt的完整URL
    robots_url = parse.urljoin(url_base, 'robots.txt')
    
    try:
        # 发送HEAD请求获取状态码
        req = request.Request(robots_url, method='HEAD')
        with request.urlopen(req) as response:
            status_code = response.getcode()
            
            if status_code == 200:
                # 文件存在,初始化robotparser并解析
                parser = robotparser.RobotFileParser()
                parser.set_url(robots_url)
                parser.read()
                print(f"✅ robots.txt存在,状态码:{status_code}")
                return status_code, parser
            else:
                print(f"❌ robots.txt无法访问,状态码:{status_code}")
                return status_code, None
                
    except request.HTTPError as e:
        # 捕获HTTP错误(比如404、403)
        print(f"❌ 请求出错:{e.code} - {e.reason}")
        return e.code, None
    except Exception as e:
        # 处理其他异常(比如网络连接问题)
        print(f"❌ 发生未知错误:{str(e)}")
        return None, None

# 调用示例
if __name__ == "__main__":
    status, parser = get_robots_status_and_parser('https://google.com/')
    # 如果需要解析内容,可以在这里继续操作parser
    # 比如检查是否允许某个爬虫访问:
    # if parser:
    #     print(parser.can_fetch("*", "https://google.com/search"))

补充说明:

  • 为什么用HEAD请求?因为它只返回响应头信息,不需要下载整个robots.txt文件,能节省带宽和时间
  • 如果HEAD请求被目标网站拒绝(比如返回405 Method Not Allowed),可以把请求方法换成GET,逻辑是一样的
  • robotparser的read()方法内部其实也是发送GET请求,但它不会暴露状态码,所以我们提前一步自己检查状态更灵活

内容的提问来源于stack exchange,提问作者nipunasudha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:20:20