>  기사  >  백엔드 개발  >  PHP를 사용하여 크롤러를 작성하는 방법을 자세히 설명하는 기사

PHP를 사용하여 크롤러를 작성하는 방법을 자세히 설명하는 기사

藏色散人
藏色散人앞으로
2021-07-17 15:44:097651검색

크롤러라고 하면 모든 사람의 첫인상은 Python일 것입니다. 하지만 Python을 모두가 아는 것은 아니므로 다른 언어를 사용하여 크롤러를 작성할 수 있을까요? 물론 가능합니다. PHP를 사용하여 크롤러를 작성하는 방법을 소개하겠습니다.

페이지의 HTML 콘텐츠 가져오기

1. 전체 파일을 문자열로 읽으려면 file_get_contents 함수를 사용하세요.

file_get_contents(path,include_path,context,start,max_length);
file_get_contents('https://fengkui.net/');

이런 방식으로 전체 페이지의 html 콘텐츠를 문자열로 읽은 다음 구문 분석할 수 있습니다.

2. CURL을 사용하여 요청하고 html을 얻습니다

/**
 * [curlHtml 获取页面信息]
 * @param  [type] $url [网址]
 * @return [type]      [description]
 */
function curlHtml($url)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL            => "{$url}",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => "GET",
        CURLOPT_HTTPHEADER     => array(
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding: gzip, deflate, br",
            "Accept-Language: zh-CN,zh;q=0.9",
            "Cache-Control: no-cache",
            "Connection: keep-alive",
            "Pragma: no-cache",
            "Upgrade-Insecure-Requests: 1",
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
            "cache-control: no-cache"
        ),
    ));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) return false;
    else return $response;
}

Curl을 사용하여 다음과 같은 다른 작업을 수행할 수 있습니다. 시뮬레이션된 탐색 서버는 로그인 및 일부 기타 고급 작업을 시뮬레이션합니다.

페이지 HTML을 구문 분석하고 필요한 데이터를 얻습니다

1. 정기적으로 콘텐츠를 얻습니다

/**
 * [get_tag_data 使用正则获取html内容]
 * @param  [type] $html  [爬取的页面内容]
 * @param  [type] $tag   [要查找的标签]
 * @param  [type] $attr  [要查找的属性名]
 * @param  [type] $value [属性名对应的值]
 * @return [type]        [description]
 */
function get_tag_data($html,$tag,$attr,$value){
    $regex = "/<$tag.*?$attr=\".*?$value.*?\".*?>(.*?)<\/$tag>/is";
    preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
    $data = isset($matches[1][0]) ? $matches[1][0] : &#39;&#39;;
    return $data;
}
$str = &#39;<div class="feng">冯奎博客</div>&#39;;
$value = get_tag_data($str, &#39;div&#39;, &#39;class&#39;, &#39;feng&#39;);

2. Xpath를 사용하여 데이터를 구문 분석합니다.

XPath는 XML 경로 언어(XML Path Language)에 사용되는 방법입니다. XML 문서의 내용을 결정합니다. 특정 위치의 언어. 구체적인 사용 방법 및 관련 소개는 바이두 백과사전(XPath)을 참조하세요. 사용 방법:

/**
 * [get_html_data 使用xpath对获取到的html内容进行处理]
 * @param  [type]  $html [爬取的页面内容]
 * @param  [type]  $path [Xpath语句]
 * @param  integer $tag  [类型 0内容 1标签内容 自定义标签]
 * @param  boolean $type [单个 还是多个(默认单个时输出单个)]
 * @return [type]        [description]
 */
function get_html_data($html,$path,$tag=1,$type=true)
{
    $dom = new \DOMDocument();
    @$dom->loadHTML("<?xml encoding=&#39;UTF-8&#39;>" . $html); // 从一个字符串加载HTML并设置UTF8编码
    $dom->normalize(); // 使该HTML规范化
    $xpath = new \DOMXPath($dom); //用DOMXpath加载DOM,用于查询
    $contents = $xpath->query($path); // 获取所有内容
    $data = [];
    foreach ($contents as $value) {
        if ($tag==1) {
            $data[] = $value->nodeValue; // 获取不带标签内容
        } elseif ($tag==2) {
            $data[] = $dom->saveHtml($value);  // 获取带标签内容
        } else {
            $data[] = $value->attributes->getNamedItem($tag)->nodeValue; // 获取attr内容
        }
    }
    if (count($data)==1) {
        $data = $data[0];
    }
    return $data;
}

추천 학습: "PHP 비디오 튜토리얼"

위 내용은 PHP를 사용하여 크롤러를 작성하는 방법을 자세히 설명하는 기사의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 fengkui.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제