php 掃描網站 獲取指定有用資訊 獲取img標籤 獲取a標籤 獲取div標籤的值或者屬性值
阿新 • • 發佈:2021-07-05
使用php7 自帶的DomDocument 獲取標籤 或者標籤屬性值 DOMDocument attribute getElementByTagName
研究一下掃描網站,獲取指定有用資訊
A.需求:
獲取<IMG><A>標籤中的內容
B.具體處理過程
1.獲取目標網站的內容
2. 利用php7 自帶的DOMDocument
C. 實現程式碼
WebGrab.php
<?php namespace Application\test; class WebGrab { protected $content=false; // 獲得內容, 利用DomDocument類 public function getContent($url){ if (!$this->content) {$url = 'http://' . $url; $this->content = new \DOMDocument('1.0', 'utf-8'); $this->content->preserveWhiteSpace = false; // @符號用於過濾掉配置錯誤的網頁所生成的警告 @$this->content->loadHTMLFile($url); } return $this->content; } // 獲取指定的標籤 以及標籤的內容public function getTags($url,$tag){ $count=0; $result=array(); $elements=$this->getContent($url)->getElementsByTagName($tag); foreach ($elements as $node){ $result[$count]['value']=trim(preg_replace('/\s+/',' ',$node->nodeValue)); if($node->hasAttributes()){ foreach ($node->attributes as $name=>$attr){ $result[$count]['attributes'][$name]=$attr->value; } } $count++; } return $result; } // 獲取指定的屬性 public function getAttribute($url,$attr,$domain=null){ $result=array(); $element=$this->getContent($url)->getElementsByTagName('*'); foreach ($element as $node){ if ($node->hasAttribute($attr)){ $value=$node->getAttribute($attr); if ($domain){ if (stripos($value,$domain)!==false){ $result[]=trim($value); } }else{ $result[]=trim($value); } } } return $result; } }
執行程式碼:
web_grab.php
<?php hen you read this code, good luck for you. */ define('DEFAULT_URL',''); define('DEFAULT_TAG','img'); // 自己封裝的自動載入類, require __DIR__.'/../Autoload/Loader.php'; Application\Autoload\Loader::init(__DIR__.'/../..'); $test=new Application\test\WebGrab(); $url=strip_tags($_GET['url']??DEFAULT_URL); $tag=strip_tags($_GET['tag']??DEFAULT_TAG); echo json_encode( [ 'message'=>'獲取成功', 'attribute'=>$test->getAttribute($url,'src'), 'tag'=>$test->getTags($url,$tag) ]);
執行結果