For循环只迭代一次(simplehtmldom)

时间:2012-08-21 16:16:13

标签: php screen-scraping web-scraping simple-html-dom phantomjs

我有一个for循环,循环3次,在循环内,shell_exec()完成,调用二进制phantomjs并返回其输出。然后将此输出传递给simplehtmldom的str_get_html()

问题:当for循环中涉及str_get_html($html)并且$html包含网页的HTML时,只会执行第一个循环,而不是第二个或第三个循环。但是,如果我对<a>使用一些简单的$html标记,则for循环会完全迭代!

这里发生了什么,我该如何解决?

注意下面两个函数的区别(一个有效的函数和一个只循环一次的函数)是其中一个有一个注释掉的行,另一个是另一行注释掉的。

父函数 (这里的for循环不会完全迭代)

public function action_asos() {


    // Site details
    $base_url = "http://www.mysite.com";

    // Category details
    $category_id = 7616;
    $per_page = 500;

    // Find number of pages in category
    $num_pages = 2;

    //THIS IS THE LOOP THAT CANNOT LOOP COMPLETELY!
    // Extract Product URLs from Category page
    for($i = 0; $i <= $num_pages; $i++) {
        echo "<h2>Page $i</h2>";
        $page = $i;
        $category_url = 'http://www.mysite.com/pgecategory.aspx?cid='.$category_id.'&parentID=-1&pge='.$page.'&pgeSize='.$per_page.'&sort=1';
        $this->extract_product_urls($category_url, $base_url);
    }
        echo "Yes.";
        flush();

}

PHP代码(导致父函数循环只循环一次)

public function extract_product_urls($category_url, $base_url) {


    set_time_limit(300);
    include_once('/home/mysite/public_html/application/libraries/simple_html_dom.php');

    // Retrieve page HTML using PhantomJS
    $html = $this->get_html($category_url);

    // Extract links
    $html = str_get_html($html);
    //$html = str_get_html('<a class="productImageLink" href="asdasd"></a>');
    foreach($html->find('.productImageLink') as $match) {
        $product_url = $base_url . $match->href;
        $product_url = substr($product_url, 0, strpos($product_url, '&'));  // remove metadata in URL string
        $this->product_urls[] = $product_url;
    }

    echo "done.";
    flush();

}

帮助程序功能

/**
 * Gets the webpage's HTML (after AJAX contented has loaded, using PhantonJS)
 * @return [type] [description]
 */
public function get_html($url) {

    $url = escapeshellarg($url);    // prevent truncating after characters like `&`
    $script = path('base')."application/phantomjs/httpget.js";
    $output = shell_exec("phantomjs $script $url");

    return $output;

}

1 个答案:

答案 0 :(得分:1)

试试这个:

while($match = $html->find('.productImageLink')) {
    if (!is_object($match)) {
        break;
    } 
    . 
    . 
    .  
}