0

我一直在寻找一个 PHP 脚本来从几个网站上抓取图像,但我找不到一个通用且允许抓取多个页面的脚本。所以我构建了一个。

它要求保存路径和要从中刮取图像的网页列表,以逗号分隔。该脚本以逗号分解用户输入的网页,然后循环浏览每个网页。它总是会很好地抓取第一个网页,但随后会跳过其余网页。

这是整个脚本。随意将它复制到 localhost 并运行它,你会明白我的意思。

<?php
error_reporting( 0 );

if(isset($_POST['doit'])){
    $scrapethese = explode(",",$_POST['website']);
    foreach($scrapethese as $scrapethis){
        $cleanit = str_replace(" ", "", $scrapethis);
        $html = file_get_contents($cleanit);
        $dom = new domDocument;
        $dom->loadHTML($html);
        $dom->preserveWhiteSpace = false;
        $imgs = $dom->getElementsByTagName('img');
        foreach($imgs as $img){
            $fullimgpath = $img->getAttribute('src');
            $slashexp = explode('/', $fullimgpath);
            $lastindex = count($slashexp)-1;
            $shortpath = $slashexp[$lastindex];
            $filename = $_POST['folder']."\\".$shortpath;
            if(copy($fullimgpath, $filename)){
                echo $slashexp[$lastindex]." Saved<br />";
            }else{
                echo "<b style='color:red;'>Could not save img: </b>".$filename."<br />";
            }
        }
    }
}else{
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="doit" value="x" />
    <label>The complete path to the page you'd like to scrape. You may enter multiple paths seperated by commas.</label><br />
    <textarea name="website" /></textarea><br />
    <label>Path to the folder you want to save images to</label><br />
    <input type="text" name="folder" /><br />
    <input type="submit" value="save all images" />
</form>
<?php
}
?>

如果有人可以提供一些见解,说明为什么在提供多个网站时脚本没有循环遍历所有网站,我将不胜感激。

4

0 回答 0