Code前端首页关于Code前端联系我们

php抓取网页div内容,php截取网页指定内容

terry 3年前 (2023-09-30) 阅读数 47 #PHP
文章标签 str_replace函数

本文目录一览:

  • 1、php怎么获取远程页面中的一个div的内容
  • 2、php如何获取一个网页中,指定某个div块的内容
  • 3、php抓取div内容
  • 4、PHP html正则提取div数据

php怎么获取远程页面中的一个div的内容

获取远程页面可以用file_get_contents()函数或者curl拓展,后者的效率会更好,但需要你修改一些配置。

查找html页面中的内容或者用phpQuery或这个:

或者用php原生的:

或者用正则。

php如何获取一个网页中,指定某个div块的内容

simple_html_dom这个通过筛选CLASS是可以获得的,但是速度较慢。建议自己通过正则表达式确定想要或取的div块。

php抓取div内容

?php  

$text = file_get_contents('');  

preg_match_all('/div id="hp_text" class="largeText"([^\/div]+)\/div/', $text, $arr);

var_dump($arr[1]);

?

输出:

array (size=1)

 0 = string '有那么个地方,曾经让你想逃;有那么个地方,生活过才知晓;有那么个地方,听别人讲起你会心怀骄傲;有那么个地方,一直是你心底的宝。' (length=189)

PHP html正则提取div数据

正则提取div数据主要是使用PHP的file_get_content()函数。

具体示例:

HTML代码:

div class="chartInfo"  

 div class="line"/div

 div class="tideTable"  

     strong潮汐表/strong数据仅供参考

     table width="500" border="0" cellspacing="0" cellpadding="0" 

       tbodytr  

  td width="100"pspan潮时 (Hrs)/span/p/td  

     td width="100"p00:58/p/td

     td width="100"p05:20/p/td

     td width="100"p13:28/p/td

     td width="100"p21:15/p/td

          /tr  

       tr  

  tdpspan潮高 (cm)/span/p/td  

     td width="100"p161/p/td  

     td width="100"p75/p/td  

     td width="100"p288/p/td  

     td width="100"p127/p/td  

          /tr  

     /tbody/table  

    h2时区:-1000 (东10区)  潮高基准面:在平均海平面下174CM/h2  

       /div  

 div class="chart"  

 /div  

/div

首页先用file_get_content或curl获取内容部分

PHP的正则处理程序:

?php

$ch = curl_init();  

curl_setopt($ch, CURLOPT_URL, $url);  

curl_setopt($ch, CURLOPT_POST, 1);  

curl_setopt( $ch, CURLOPT_HEADER, 0 );  

curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );  

curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );  

$return = curl_exec( $ch );  

curl_close( $ch );  

 

$regex4="/div class=\"tideTable\".*?.*?\/div/ism";  

if(preg_match_all($regex4, $return, $matches)){  

   print_r($matches);  

}else{  

   echo '0';  

}

?

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

热门