发表于 2015/03/12 | 来自 雷鬼
有时,我们需要一些小手段快速增加网站内容,譬如爬虫(^o^)/~
那么,我们如何才能做到,通过调用typecho的api快速插入文章呢?
通过分析代码,发现创建文章的逻辑挺复杂的,即关联较多。那么如何可以方便调用呢?通过抓包发现,原来我们可以直接调用Widget_Contents_Post_Edit进行插入。
接下来,我们一步一步讲解,如何调用typechoapi创建或者插入文章。
如果对插件不熟悉,请移步到本站的插件专区进行了解哈。
1.爬虫从网上扒取文章
假设爬虫只扒取了文章标题和文章内容,那么,我们可以假设爬虫会将title和text两个字段内容post过来。
那么在我们的Widget中,可以通过$request获取提交过来的内容。
2.设置作者信息
在Typecho中,每篇文章的创建均需要管理到一个有“编辑”权限的用户。在我们的widget中,通过Widget_User来进行权限设定。
$user="创建此文章的用户,注意要有权限";
$password="用户对应的密码";
if (!$this->user->hasLogin()) {
if (!$this->user->login($user, $password, true)) { //使用特定的账号登陆
die('登录失败');
}
}
3.调用Widget_Contents_Post_Edit进行文章导入
使用Request组件来设定文章信息,然后调用Widget_Contents_Post_Edit组价来进行文章导入。
$request->setParams(
array(
'title'=>$title,
'text'=>$text,
...
)
);
//执行添加文章操作
$widgetName = 'Widget_Contents_Post_Edit';
$reflectionWidget = new ReflectionClass($widgetName);
if ($reflectionWidget->implementsInterface('Widget_Interface_Do')) {
$this->widget($widgetName)->action();
echo 'Successful';
return;
}
4.附上完整代码
class MyPlugin_NewPost extends Widget_Abstract_Contents implements Widget_Interface_Do {
public function __construct($request, $response, $params = NULL) {
parent::__construct($request, $response, $params);
}
public function action() {
$user="创建此文章的用户,注意要有权限";
$password="用户对应的密码";
if (!$this->user->hasLogin()) {
if (!$this->user->login($user, $password, true)) { //使用特定的账号登陆
die('登录失败');
}
}
$request = Typecho_Request::getInstance();
$title = $request->get('title');
$text = $request->get('text');
//填充文章的相关字段信息。
$request->setParams(
array(
'title'=>$title,
'text'=>$text,
'fieldNames'=>array(),
'fieldTypes'=>array(),
'fieldValues'=>array(),
'cid'=>'',
'do'=>'publish',
'markdown'=>'1',
'date'=>'',
'category'=>array(),
'tags'=>'',
'visibility'=>'publish',
'password'=>'',
'allowComment'=>'1',
'allowPing'=>'1',
'allowFeed'=>'1',
'trackback'=>'',
)
);
//设置token,绕过安全限制
$security = $this->widget('Widget_Security');
$request->setParam('_', $security->getToken($this->request->getReferer()));
//设置时区,否则文章的发布时间会查8H
date_default_timezone_set('PRC');
//执行添加文章操作
$widgetName = 'Widget_Contents_Post_Edit';
$reflectionWidget = new ReflectionClass($widgetName);
if ($reflectionWidget->implementsInterface('Widget_Interface_Do')) {
$this->widget($widgetName)->action();
echo 'Successful';
return;
}
}
}
接着,通过添加路由,使爬虫能够请求到此Widget即可。
Helper::addAction('import', 'MyPlugin_NewPost');
最后,爬虫通过往http://127.0.0.1/index.php/action/import地址post数据即可。附上js的伪代码:
var url = http://127.0.0.1/index.php/action/import
$.post(url,{
title:'your title',
'text':'your post text',
'sign':'your hash sign'//增加安全校验码,避免其他人向此接口恶意请求
});
最新回复