【问题标题】:Repeat until true重复直到为真
【发布时间】:2015-12-18 01:13:35
【问题描述】:

如何重复此功能,直到找到我正在寻找的图像类?假设 img.header 只存在于给定的一些随机 id 范围内。请不要使用标题。

<?php

include('simple_html_dom.php');

$randomID = mt_rand(100, 1000);
$url = "http://newspaper.com/article/".$randomID;

// Create DOM from URL or file
$html = file_get_html($url);

//Find img
$element = $html->find('img.header');

//Check if image was found              
if (strpos($element,'img') == false) {
    ///////////////////////////////////////////
    //Repeat until find('img.header') is true//
    ///////////////////////////////////////////
} else {
    echo $element->src;
}

?>

【问题讨论】:

  • 为此做一个小提琴以获得快速答案
  • 这个函数的`print_r()`有什么作用? $dom = str_get_html(file_get_contents($url));
  • @jimmyobonyo 我如何在其中包含简单的 html dom?
  • 什么,print_r($element)?
  • 如果你没有关于你正在寻找的元素分布的信息,扫描页面 1,2,3,4,5 对网站来说就像使用随机 ID 一样富有成效和压力(如果您因为重新扫描而没有跟踪先前扫描的 id,后者实际上会更糟)。

标签: php html dom html-parsing


【解决方案1】:

许多可能的方法,其中一种比较简单的例子:

<?php
$ids = range(100, 400000); // RAM is so cheap
shuffle($ids); // still not convinced it makes a difference, but why not...

foreach( $ids as $index=>$id ) {
    // <-- maybe you want to add some output here, so you can see that the script is still running.
    $url = "http://newspaper.com/article/".$id;
    $html = file_get_html($url);
    // edit: <-- some error handling here. See documentation of simple_html_dom on how to check $html for error conditions
    $element = $html->find('img.header');
    if ( $element ) {
        // found it
        // and the ids you've had to visit before finding the element are
        $visited = array_slice($ids, 0, $index+1);  
        break; // no need to go on, exit foreach-loop
    }
}

if ( !isset($visited) ) {
    // the element was never found....
}
else {
    // $html, $element and even $id should be still valid
    // so, you can use them here for further processing
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 2021-07-13
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多