前言
笔者平日闲暇会在网易新闻里浏览新闻,之前发过一篇Alfred Workflow基于Python的入门案例,主要逻辑是输入内容之后直接显示item
内容,操作比较单调。于是通过进一步学习Alfred Workflow,可以将在item
中选择参数传入,以此激活下一个Action
。笔者在此基础上利用Python的BeautifulSoup
爬虫库写了一个浏览网易新闻头条的Workflow。
效果
步骤
- 创建一个空的workflow程序 ,添加一个Script Filter
- 添加一个Open URL Action
- 代码分析
# -*- coding:utf-8 -*-
#导入需要使用到的模块
import sys
import urllib2
from workflow import Workflow
from bs4 import BeautifulSoup
def main(wf):
#加载url读取到的页面元素
html = urllib2.urlopen(url="http://news.163.com/").read()
#转换为BeautifulSoup对象
bsObj = BeautifulSoup(html)
#获取头条新闻所在的标签内容
title_big_2_set = bsObj.find("div", {"class": "mod_top_news2"}).find_all("a")
#遍历头条新闻内容
for i in title_big_2_set:
#title:item的标题,当前为头条新闻文本内容;arg:传递的参数,当前为头条新闻内容的链接;valid:是否激活下一个action,当前为True
wf.add_item(title=i.get_text(),arg=i.attrs['href'],valid=True)
wf.send_feedback()
if __name__ == u"__main__":
wf = Workflow()
sys.exit(wf.run(main))
- 将Script Filter和Open URL连接
结尾
- 以前浏览新闻:移动鼠标——打开浏览器(鼠标点击一次)——打开网易新闻(鼠标点击两次)——浏览新闻(移动鼠标)——打开新闻内容(鼠标点击两次)。
- 现在浏览新闻:快捷键打开Alfred(笔者是敲击两次
command
)——键入「news」——浏览新闻——回车打开新闻内容。
比起之前,在Alfred中浏览使得这件事更加轻松快速了许多。