Web 크롤링/PHP Crawling

네이버 증권 오늘의 종가 및 고가 크롤링

Link2Me 2024. 8. 18. 21:20
728x90

네이버 증권 오늘 날짜, 종가 및 고가 정보를 크롤링하는 PHP 코드이다.

 

<?php
error_reporting(0);
//*
ini_set("display_startup_errors"1);
ini_set("display_errors"1);
error_reporting(E_ALL);
// */
 
require_once $_SERVER['DOCUMENT_ROOT'].'/simple_html_dom.php';
 
$code = '001740';
 
 
    $url = "https://finance.naver.com/item/main.naver?code=".$code;
 
    // 웹페이지에서 HTML 데이터 가져오기
    $ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
    $options = [
        "http" => [
            "header" => "User-Agent: " . $ua
        ]
    ];
    $context = stream_context_create($options);
    $html = file_get_html($urlfalse$context);
    $enc = mb_detect_encoding($htmlarray('EUC-KR''UTF-8''shift_jis''CN-GB')); // HTML의 인코딩을 감지
    if ($enc != 'UTF-8') { // 감지된 인코딩이 UTF-8이 아닌 경우 변환
        $html = iconv($enc'UTF-8'$html);
    }
    $html = str_get_html($html);
 
    if ($html !== false) {
 
        $stock_day = $html->find('div.description #time em.date',0)->plaintext;
        $date_today = substr($stock_day,0,10);
 
        $stock_curval = $html->find('#chart_area div.rate_info p.no_today',0);
 
        if ($stock_curval) { 
            $stock_close = $stock_curval->find('em.no_up span'0); // 종가 상승
 
            if (!$stock_close) { 
                $stock_close = $stock_curval->find('em.no_down span'0); // 종가 하락
            }
            
            if (!$stock_close) {
                $stock_close = $stock_curval->find('span.blind'0); // 종가 보합
            }
 
            if ($stock_close) {
                $close = preg_replace("/[^0-9]/"""$stock_close->plaintext); // 오늘의 종가
            }
        }
 
        $stock_hval = $html->find('#chart_area div.rate_info table tr td:nth-child(2)',0);
        if ($stock_hval) { 
            $stock_high = $stock_hval->find('em.no_up span'0); // 고가 상승
 
            if (!$stock_high) { 
                $stock_high = $stock_hval->find('em.no_down span'0); // 고가 하락
            }
            
            if (!$stock_high) {
                $stock_high = $stock_hval->find('span.blind'0); // 종가 보합
            }
 
            if ($stock_high) {
                $todayHigh = preg_replace("/[^0-9]/"""$stock_high->plaintext); // 오늘의 고가
            }
        }
 
        echo $date_today.'<br/>';
        echo $close.'<br/>';
        echo $todayHigh.'<br/>';
 
    }
?>

 

 

728x90