另一个基于对象的黑客新闻api的python包装器。
hnp的Python项目详细描述
一个用python编写的黑客新闻api包装器
目的
本文的目标是在 命名和结构,但是使用 python对象。
安装
根据您的系统配置,使用下列选项之一:
pip install hnpy pip3 install hnpy python3 -m pip install hnpy
用法
创建主类的实例,如下所示:
importhnpyhn=hnpy.HackerNews()
项目
如果您知道某个项目的ID,您可以这样访问它:
post=hn.item(8863)
项目可以是五种类型之一:“工作”、“故事”、“评论”、“投票”或 “pollopt.”您可以通过访问post.type来确定其类型。
项目对象被延迟加载,这意味着它们只发出网络请求 当需要他们还没有的信息时。
可以检查项与其他项或ID是否相等 以int或str形式。
项具有各种属性,这些属性取决于它们的类型。你可以用 hasattr()以编程方式确定某个项是否 是否属性。更多关于属性的信息 here。属性名 hnpy是从api中的字段名复制的。
项目有五个特殊属性:
Attribute name | Explanation |
---|---|
content | The “meat” of the Item — ^{tt5}$, ^{tt6}$, or ^{tt7}$, with a fallback to an empty string if none exist. |
link | URL to access the Item. |
parent | Item that this one replies to (not always present). |
poll | Item of type ^{tt8}$ that this one belongs to (only present on ^{tt9}$ Items). |
by | User who created this Item. |
这里指出了link和content属性,因为api 不直接提供,因此在其他地方没有记录。 注意parent、poll和by属性,因为它们 包含全功能、延迟加载的项,而不仅仅是id API的响应。其余的items属性是 以从api接收到的相同格式交付。
可以这样访问属性:
post.contentpost.linkpost.parentpost.pollpost.by
items还有两个特殊的方法来迭代和传递items。每个 接受默认为25的可选limit=参数。
Method name | Use |
---|---|
kids() | Iterate over the comments that reply to this Item. |
parts() | Iterate over the options of this Item (only present on ^{tt8}$ types). |
方法如下:
forkidinpost.kids(limit=5):print(kid.content)foroptinpost.parts():print(opt.content)
列表
您可以使用hnpy查看hacker news提供的以下列表:
- 顶部(这是Hacker News主页上显示的视图)
- 最佳
- 新的
- 询问hn故事
- 显示hn故事
- 工作经历
就像一个项目的特殊方法,黑客的这些方法 对象采用可选的limit=参数。它们在 指定的列表,在运行时生成惰性项。
示例:
forpostinhn.best(limit=5):print(post.link)
方法名为:
- top()
- best()
- new()
- ask()
- show()
- jobs()
用户
可以使用^{tt24}从用户名创建用户$ 方法:
user=hn.user('jl')
除了属性noted in the Hacker News API documentation,用户 包含以下属性和方法:
Attribute/method name | Purpose |
---|---|
link | A URL to view the User’s profile online. |
submitted() | Iterate over Items created by the user, with optional ^{tt15}$ parameter. |
其他
hackernews对象有一个方法updates(),该方法返回 更新对象,该对象具有与其他对象一样的迭代方法 对象(可选的limit=参数,产生的对象)提供 最近更改的项目和配置文件(更多信息 here)。 它的两个方法是items()和profiles()。
hackernews对象还有一个方法max_item(),它返回 最新项目的懒惰版本。
学分
这个包最初来自我的A Bot项目。它适应了 支持对象的延迟加载,因此只有四个 类(hackernews、item、user、updates),而不是有一个类 对于具有复杂继承模型的每种类型的项。本版本 还支持旧版本没有的用户和更新。
这个包的灵感来自python reddit api包装器aka praw (docs/source) 在使用对象和迭代方法以及limit=参数时。