我正在使用 curl 进行网页抓取,并且可以显示感兴趣的结果。
通常,下面的脚本会向我输出 WEB SCRAPER TESTING GROUND 文本,该文本由页面中的“标题”ID 进行刮取和正则表达式。
现在我想检查 $list 数组中是否存在“TESTING”这个词。如果是 - 只是回声“存在”,如果不是 - 回声“不存在”。做这个的最好方式是什么?
我知道如何搜索网页并从中提取文本部分。
$curl = curl_init('http://testing-ground.scraping.pro/textlist'); // cURL
setup
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // return the transfer
page as a string
curl_setopt($curl, CURLOPT_HEADER, TRUE);
$page = curl_exec($curl); // executing the request
if(curl_errno($curl)) // check for execution errors
{
echo 'Scraper error: ' . curl_error($curl);
exit;
}
curl_close($curl); // closing the connection
$regex = '/<div id="title">(.*?)<\/div>/s'; // extracting the needed part
if ( preg_match($regex, $page, $list) ) // search matches of $page with
$regex
echo $list[0];
else
print "Not found";
我知道如何搜索网页并从中提取文本部分。
实际上,你做错了。代码实际上应该看起来像
$list[]=(@DOMDocument::loadHTML($page))->getElementById("title")->textContent;
如果您想学习如何在 PHP 中正确解析 HTML,请阅读主题 >如何在 PHP 中解析和处理 HTML/XML?
现在我想检查 $list 数组中是否存在“TESTING”这个词。如果是 - 只是回声“存在”,如果不是 - 回声“不存在”。做这个的最好方式是什么?
找到一个布尔值,用 foreach 迭代它,用 strpos() 检查列表中的每个条目,如果找到它,请确保尽早中断循环(因为在匹配后继续循环将浪费 CPU 和时间找到),最后打印结果,例如
$found=false;
foreach($list as $foo){
if(false!==strpos("TESTING",$foo)){
$found=true;
break;
}
}
if($found){
echo "present";
}else{
echo "not present";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句