-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
40 lines (27 loc) · 1.06 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import io
class PostsWriter:
def __init__(self, fp: io.TextIOBase, title: str):
self.fp = fp
self.title = title
def write(self, posts: List[Post]):
self.fp.write(f'# {self.title}\n\n')
# enumerate 接收第二个参数,表示从这个数开始计数(默认为 0)
for i, post in enumerate(posts, 1):
self.fp.write(f'> TOP {i}: {post.title}\n')
self.fp.write(f'> 分数:{post.points} 评论数:{post.comments_cnt}\n')
self.fp.write(f'> 地址:{post.link}\n')
self.fp.write('------\n')
class HNTopPostsSpider:
ITEMS_URL = 'https://news.ycombinator.com/'
FILE_TITLE = 'Top news on HN'
def __init__(self, fp: io.TextIOBase, limit: int = 5):
self.fp = fp
self.limit = limit
def write_to_file(self, fp: io.TextIOBase):
writer = PostsWriter(fp, title=self.FILE_TITLE)
writer.write(list(self.fetch()))
def main():
crawler = HNTopPostsSpider(sys.stdout)
crawler.write_to_file()
if __name__ == '__main__':
main()