[英]Simple Html DOM Caching
我正在使用簡單HTML DOM抓取(獲得許可)某些網站。 我基本上用統計數據抓取了大約50個不同的網站,這些數據每天大約更新四次。
如您所料,進行抓取需要花費時間,因此我需要通過進行一些緩存來加快過程。
我的願景是:
DATA-PRESENTATION.php //顯示所有結果
SCRAPING.php //完成任務的代碼
我想以一種每天執行4次的方式在SCRAPING.PHP上設置cron作業,並將所有數據保存在caché中,然后DATA-PRESENTATION.PHP會請求該數據,從而使用戶體驗更快。
我的問題是我該如何實施此caché的東西? 我是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 Job,告訴它每次都覆蓋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é文件要加載。
這是基於文件的緩存的示例:
<?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");
?>
嘗試使用Zend_Framework中的Zend_Cache庫。 使用起來非常簡單:
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'];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.