我对OOP很陌生,所以请怜悯;(。如果这篇文章的标题没问题,我什至不舒尔。
我正在用Goutte
抓取一些网站,像这样
$ad['title'] = $crawler->filter('#subject')->text();
$ad['image'] = $crawler->filter('.images')->filter('meta')->eq(0)->attr('content');
这不是太难,但我希望有可重用的代码。因此,对于我抓取的每个站点,都有一个$ad['title']
和一个$ad['image']
使用的$crawler方法因站点而异,因此我希望具有类似
$crawler->$filter
其中筛选器包含
'filter('#subject')->text()'
这样,我可以将过滤器存储在每个站点的数据库中。我不知道这是否可能甚至是一个好方法。
处理问题的一种方法是使用 OOP 多态性概念。对于 PHP,这里对此进行了解释,在您的情况下可以像这样使用(大大简化):
为爬网程序定义一个抽象类。每个爬网程序都必须实现扩展它并提供自己的实现。当然,爬网程序类将嵌入$crawler
对象。
abstract class BaseCrawler
{
protected $crawler;
abstract protected function getTitleElement();
abstract protected function getImageElement();
// initialize the crawler etc.
}
class CrawlerOne extends BaseCrawler
{
public function getTitleElement()
{
// get the title for crawler one
}
public function getImageElement()
{
// get the image for crawler one
}
// other functionality may come here
}
class CrawlerTwo extends BaseCrawler
{
public function getTitleElement()
{
// get the title for crawler two
}
public function getImageElement()
{
// get the image for crawler two
}
// other functionality may come here
}
因此,您的结构是灵活的,但具有通用功能。
数据库用于存储数据,而不是逻辑。因此,如果标题和图像可以使用简单的正则表达式获取,则可以将其存储在每个爬网程序的数据库中。在这种情况下,每个爬网程序都可以定义一个常量代码,该代码可用于执行标题和图像正则表达式的查找。