我使用简单的HTML (经许可)刮一些网站。我基本上用统计数据刮了大约50个不同的网站,大约每天更新四次。
正如您可以想象的那样,执行抓取需要花费时间,因此我需要通过进行一些缓存来加快这个过程。
我的愿景是:
DATA-PRESENTATION.php //其中显示了所有结果
SCRAPING.php //使作业生成的代码
我想在SCRAPING.PHP上设置一个cron作业,它每天执行4次,并将所有数据保存在caché中,然后由DATA-PRESENTATION.PHP请求这些数据,使用户的体验更快。
我的问题是,我怎样才能实现这一点?我是PHP的新手,我一直在阅读教程,但它们不是很有帮助,只有几个,所以我只是不能真正学会如何去做。
我知道其他解决方案可能正在实现一个数据库,但我不想这样做。此外,我一直在阅读有关像memcached这样的高端解决方案的文章,但是这个网站非常简单,而且是供个人使用的,所以我不需要这样的东西。
谢谢!!
SCRAPING.PHP
<?php
include("simple_html_dom.php");
// Labour stats
$html7 = file_get_html('http://www.website1.html');
$web_title = $html7->find(".title h1");
$web_figure = $html7->find(".figures h2");
?>
DATA-PRESENTATION.PHP
<div class="news-pitch">
<h1>Webiste: <?php echo utf8_encode($web_title[0]->plaintext); ?></h1>
<p>Unemployment rate: <?php echo utf8_encode($web_figure[0]->plaintext); ?></p>
</div>
最终代码!谢谢@jerjer和@PaulD.Waite,没有你的帮助,我真的做不到!
文件:
1- DataPresentation.php //这里显示了向Cache.html请求的数据
2- Scraping.php //我在这里刮刮站点,然后将结果保存到Cache.html
3- Cache.html //在这里保存刮取结果
我在Scraping.php上设置了一个Cron作业,告诉它每次都要覆盖Cache.html。
1- DataPresentation.php
<?php
include("simple_html_dom.php");
$html = file_get_html("cache/test.html");
$title = $html->find("h1");
echo $title[0]->plaintext;
?>
2- Scraping.php
<?php
include("simple_html_dom.php");
// by adding "->find("h1")" I speed up things as it only retrieves the information I'll be using and not the whole page.
$filename = "cache/test.html";
$content = file_get_html ('http://www.website.com/')->find("h1");
file_put_contents($filename, $content);
?>
3- Cache.html
<h1>Current unemployment 7,2%</h1>
它会立即加载,通过这样设置,我保证总是有一个Caché文件要加载。
发布于 2011-12-15 09:07:44
下面是一个基于文件的缓存示例:
<?php
// Labour stats
$filename = "cache/website1.html";
if(!file_exists($filename)){
$content = file_get_contents('http://www.website1.html');
file_put_contents($filename, $content);
}
$html7 = file_get_html($filename);
$web_title = $html7->find(".title h1");
$web_figure = $html7->find(".figures h2");
?>
发布于 2011-12-15 10:07:17
尝试使用来自Zend_Cache的Zend_Framework库。使用起来非常简单:
function loadHtmlWithCache($webAddress){
$frontendOptions = array(
'lifetime' => 7200, // cache lifetime of 2 hours
'automatic_serialization' => true
);
$backendOptions = array(
'cache_dir' => './tmp/' // Directory where to put the cache files
);
// getting a Zend_Cache_Core object
$cache = Zend_Cache::factory('Core',
'File',
$frontendOptions,
$backendOptions);
if( ($result = $cache->load($webAddress)) === false ) {
$html7 = file_get_html($webAddress);
$web_title = $html7->find(".title h1");
$web_figure = $html7->find(".figures h2");
$cache->save($webAddress,array('title'=>$web_title,'figure' => $web_figure));
} else {
// cache hit! shout so that we know
$web_title = $result['title'];
$web_figure = $result['figure'];
}
}
https://stackoverflow.com/questions/8517489
复制相似问题