使用php刮取网页并获取超过特定宽度和高度的图像
我可以用php从网站上抓取图像,但我想抓取第一个高度大于200px、宽度大于200px的图像。如何获取第一个图像源的尺寸?这是我的密码使用php刮取网页并获取超过特定宽度和高度的图像,php,image,web-scraping,Php,Image,Web Scraping,我可以用php从网站上抓取图像,但我想抓取第一个高度大于200px、宽度大于200px的图像。如何获取第一个图像源的尺寸?这是我的密码 $html_3 = file_get_contents('http://beignindian.com'); preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i',$html_3, $matches ); $main_image_1 = $matches[ 1 ][ 0 ]; 您可以使用函数
$html_3 = file_get_contents('http://beignindian.com');
preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i',$html_3, $matches );
$main_image_1 = $matches[ 1 ][ 0 ];
您可以使用函数获取图像的高度和宽度。一旦您得到它,然后添加if条件以执行进一步的代码
list($width, $height) = getimagesize($main_image_1); // I am assuming that $main_image_1 has image source.
echo "width: " . $width . "<br />";
echo "height: " . $height;
if($width > 200 && $height > 200) {
// perform something here.
}
你怎么知道它的宽度和高度大于200?通过使用get_image_size,第一个满足上述要求的图像我需要它的url,如果该网站中没有这样的图像,那么Null我需要爬过网站中的所有图像,而不是一个,然后你可以使用循环并检查所有图像的大小:在上述情况下,我如何循环我无法如果不这样做,一张照片中会有多少张wesite@sravyanaidu:检查我的更新答案。祝你一切顺利!感谢您提供的信息,但我有一个疑问,一旦我发现第一个图像的宽度和高度大于200px,我需要停止它并存储在varibla中
$host = "http://www.beingindian.com/";
$html = file_get_contents($host);
// create new DOMDocument
$document = new DOMDocument('1.0', 'UTF-8');
// set error level
$internalErrors = libxml_use_internal_errors(true);
// load HTML
$document->loadHTML($html);
// Restore error level
libxml_use_internal_errors($internalErrors);
$images = $document->getElementsByTagName('img');
foreach ($images as $image) {
$image_source = $image->getAttribute('src');
// check if image URL is an absolute URL or relative URL
$image_url = (filter_var($image_source, FILTER_VALIDATE_URL))?$image_source:$host.$image_source;
list($width, $height) = getimagesize($image_url);
if($width > 200 && $height > 200) {
// perform something here.
}
else {
// perform something here.
}
}