在PHP中抓取网页的照片
如果用样式写入的网址,如何从网站复制照片的网址。在PHP中抓取网页的照片
<div class="thumb">
<a href="http://goruzont.blogspot.com/2017/04/blog-post_6440.html" style="background:url(https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg) no-repeat center center;background-size:cover">
<span class="thumb-overlay"></span></a>
</div>
您可以使用正则表达式只提取背景图像或背景:URL格式
$str='
<div class="thumb">
<a href="http://goruzont.blogspot.com/2017/04/blog-post_6440.html" style="background:url(https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg) no-repeat center center;background-size:cover">
<span class="thumb-overlay"></span></a>
</div>';
preg_match_all('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$str,$matches);
$images = $matches['image'];
foreach($images as $img){
echo $img;
}
# https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg
不要将正则表达式用于HTML解析。 [托尼小马,他来了。](http://stackoverflow.com/a/1732454/1902010) – ceejayoz
@ceejayoz谢谢你提供的理由。我会看看。 –
谢谢你的帮助!请告诉我如何使url复制到所有块“拇指”? –
您可以使用DOMDocument
和DOMXPath
$html = <<< EOF
<div class="thumb">
<a href="http://goruzont.blogspot.com/2017/04/blog-post_6440.html" style="background:url(https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg) no-repeat center center;background-size:cover">
<span class="thumb-overlay"></span></a>
</div>
EOF;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//div[contains(@class,"thumb")]/a') as $item) {
$img_src = $item->getAttribute('style');
$img_src = preg_replace('/.*?\((.*?)\).*?/m', '$1', $img_src);
print $img_src;
}
# https://1.bp.blogspot.com/-6vpIH5iqPYs/WPzlNdxsRpI/AAAAAAAAntU/d7U_Ch_6FiIPwosNL4tWwqBeXw8qwo2nACLcB/s1600/1424051.jpg
谢谢你的帮助!请告诉我如何使url复制到所有块“拇指”? –
请帮助,问题是一样的,只需要复制所有块“拇指”的url图片。 –
如何复制所有块的网址照片“拇指”? –