DeepSeek - 探索ThinkPHP采集
在ThinkPHP框架中实现新闻采集功能,通常涉及以下几个步骤:
1. 安装ThinkPHP
首先,确保你已经安装并配置好了ThinkPHP框架。如果还没有安装,可以通过Composer进行安装:
composer create-project topthink/think your-project-name
2. 创建采集控制器
在ThinkPHP中,你可以创建一个控制器来处理新闻采集的逻辑。例如,创建一个CollectController
:
php think make:controller Collect
3. 编写采集逻辑
在CollectController
中编写采集新闻的逻辑。你可以使用PHP的file_get_contents
或cURL
来获取目标网站的HTML内容,然后使用正则表达式或DOM解析器(如simple_html_dom
)来提取新闻数据。
namespace appcontroller;
use thinkController; use thinkfacadeDb;
class Collect extends Controller { public function index() {
$url = 'https://example.com/news';
$html = file_get_contents($url);
preg_match_all('/<h2 class="news-title">(.*?)<\/h2>/', $html, $titles);
preg_match_all('/<div class="news-content">(.*?)<\/div>/', $html, $contents);
foreach ($titles[1] as $key => $title) {
$data = [
'title' => $title,
'content' => $contents[1][$key],
'created_at' => date('Y-m-d H:i:s'),
];
Db::name('news')->insert($data);
}
return '新闻采集完成!';
}
}
4. 配置数据库
在config/database.php
中配置数据库连接信息。确保你已经创建了news
表来存储采集到的新闻数据。
return [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'your_database_name',
'username' => 'your_username',
'password' => 'your_password',
'hostport' => '3306',
'prefix' => '',
];
5. 创建新闻表
在数据库中创建news
表:
CREATE TABLE `news` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `content` text NOT NULL, `created_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6. 运行采集任务
你可以通过访问CollectController
的index
方法来运行采集任务。例如:
然后在浏览器中访问:
http://localhost:8000/collect/index
7. 定时任务(可选)
如果你希望定期自动采集新闻,可以使用ThinkPHP的命令行工具结合操作系统的定时任务(如Linux的cron
)来实现。
创建一个命令行指令:
php think make:command CollectNews
在app/command/CollectNews.php
中编写采集逻辑:
namespace appcommand;
use thinkconsoleCommand; use thinkconsoleInput; use thinkconsoleOutput; use thinkfacadeDb;
class CollectNews extends Command { protected function configure() { $this->setName('collect:news')->setDescription('采集新闻'); }
protected function execute(Input $input, Output $output)
{
$url = 'https://example.com/news';
$html = file_get_contents($url);
preg_match_all('/<h2 class="news-title">(.*?)<\/h2>/', $html, $titles);
preg_match_all('/<div class="news-content">(.*?)<\/div>/', $html, $contents);
foreach ($titles[1] as $key => $title) {
$data = [
'title' => $title,
'content' => $contents[1][$key],
'created_at' => date('Y-m-d H:i:s'),
];
Db::name('news')->insert($data);
}
$output->writeln('新闻采集完成!');
}
}
然后可以通过以下命令手动运行采集任务:
最后,在Linux系统中设置cron
定时任务:
添加以下内容,每天凌晨1点执行采集任务:
0 1 * * * /usr/bin/php /path/to/your/project/think collect:news
总结
通过以上步骤,你可以在ThinkPHP框架中实现新闻采集功能。你可以根据实际需求调整采集逻辑和定时任务的频率。