首页
/ Robots Exclusion Protocol Parser for Python 使用与技术文档

Robots Exclusion Protocol Parser for Python 使用与技术文档

2024-12-26 16:05:47作者:昌雅子Ethen

1. 安装指南

reppy 可以在 pypi 上找到,使用以下命令进行安装:

pip install reppy

从源代码安装时,需要获取一些子模块依赖:

git submodule update --init --recursive
make install

2. 项目的使用说明

reppy 是一个用于解析 robots.txt 的 Python 库。以下是如何使用该项目的说明:

检查页面是否允许访问

RobotsAgent 两个类可以回答关于 URL 是否允许访问的问题:

from reppy.robots import Robots

robots = Robots.fetch('http://example.com/robots.txt')
robots.allowed('http://example.com/some/path/', 'my-user-agent')

agent = robots.agent('my-user-agent')
agent.allowed('http://example.com/some/path/')

Robots 类还提供了 expiredttl 属性,描述响应应被视为有效的时间长度。可以使用 reppy.ttl 策略来决定这个时间:

from reppy.ttl import HeaderWithDefaultPolicy

policy = HeaderWithDefaultPolicy(default=1800, minimum=600)

robots = Robots.fetch('http://example.com/robots.txt', ttl_policy=policy)

自定义获取方式

fetch 方法接受 *args**kwargs 参数,这些参数会传递给 requests.get,允许您自定义获取方式:

robots = Robots.fetch('http://example.com/robots.txt', headers={...})

匹配规则与通配符

*$ 都支持用作通配符匹配。如果有多条规则匹配到查询,最长的规则将获胜,因为它被认为是更具针对性的。

检查站点地图

Robots 类还可以列出在 robots.txt 中列出的所有站点地图:

robots.sitemaps

延迟

Crawl-Delay 指令针对每个代理,可以通过该类访问。如果没有指定,则为 None

robots.agent('my-user-agent').delay

确定 robots.txt 的 URL

给定一个 URL,有一个工具可以确定相应 robots.txt 的 URL。它会保留方案、主机名和端口(如果不是方案的默认端口)。

Robots.robots_url('http://userinfo@example.com:8080/path;params?query#fragment')

3. 项目 API 使用文档

以下是 reppy 的一些关键 API 的使用文档:

  • Robots.fetch(url, **kwargs): 获取并解析给定 URL 的 robots.txt 文件。
  • robots.allowed(url, user_agent): 检查指定的 URL 是否允许给定的用户代理访问。
  • robots.agent(user_agent): 获取特定用户代理的规则。
  • robots.sitemaps: 返回在 robots.txt 中列出的所有站点地图的 URL 列表。
  • robots.robots_url(url): 根据给定的 URL 确定相应的 robots.txt URL。

4. 项目安装方式

reppy 的安装方式已在“安装指南”一节中介绍。您可以通过 pip 安装预编译的包,或从源代码安装。

以上就是 reppy 项目的技术文档,希望能够帮助您更好地了解和使用该项目。

登录后查看全文
热门项目推荐