使用PHP抓取数据以加载更多?

时间:2017-09-12 09:56:00

标签: php web-crawler

我正在尝试从网站抓取数据,我也做了但问题是有加载更多按钮,我只能抓取可见数据,点击加载后出现的数据 - 更多按钮,我不能能够爬行。

使用preg_match_all:

$page = file_get_contents('https://www.healthfrog.in/chemists/medical-store/gujarat/surat');

preg_match_all(
    '/<h3><a href="(.*?)">(.*?)<\/a><\/h3><p><i class="fa fa-map-marker"><\/i>(.*?)<\/p>/s',
    $page,
    $retailers, // will contain the article data
    PREG_SET_ORDER // formats data into an array of posts
);

foreach ($retailers as $post) {
    $retailer['name'] = $post[2]; 
    $retailer['address'] = $post[3]; 
    echo "<b>".$retailer['name']."</b><br/>".$retailer['address']."<br/><br/>";
}

使用DOMDocument:

$html = new DOMDocument();
@$html->loadHtmlFile('https://www.healthfrog.in/chemists/medical-store/gujarat/surat');
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query('//*[@id="setrecord"]/div[@class="listing "]');

foreach ($nodelist as $n){
    $retailer = $xpath->query('h3/a', $n)->item(0)->nodeValue."<br>";
    $address = $xpath->query('p', $n)->item(0)->nodeValue;
    echo "<b>".$retailer."</b><br/>".$address."<br/><br/>";
}

任何想法如何一次抓取整个数据?

1 个答案:

答案 0 :(得分:0)

我认为您需要尝试以更有效的方式抓取您的网页。

我的第一个建议是在命令行中使用PhantomJs作为复杂的Web引擎。这意味着您可以执行幻像js操作(在javascript中)获取网页,触发一些dom事件并使用php exec命令获取所需的数据。

PhantomJS是一个带有JavaScript API的无头WebKit脚本。它 为各种Web标准提供快速和本机支持:DOM处理, CSS选择器,JSON,Canvas和SVG。

// Simple Javascript example

console.log('Loading a web page');
var page = require('webpage').create();
var url = 'http://phantomjs.org/';
page.open(url, function (status) {
  //Do your dom operations( click read more button or anything else) and just console.log(yourDataThatYouNeed)
  phantom.exit();
});

为了获取PhantomJs的php驱动程序所需的数据。

这里有一个示例Php Client For PhantomJS =&gt; https://github.com/jonnnnyw/php-phantomjs

Actualy我有一个用于phantomJs的php驱动程序,我作为一个副项目开发,我计划在接下来几天在我的github帐户上发布。

我建议你使用像scrapy这样的抓取框架的第二种方式(坦率地说,我认为对于复杂项目是正确的)。您可以查看documentation如何使用scrapy从网页抓取数据。

Scrapy是一个功能强大的框架,用于根据python从网站中提取所需的数据。

您可以查看本教程中的scrapy https://docs.scrapy.org/en/latest/intro/tutorial.html