티스토리 뷰
PHP에서 curl를 이용해서 웹크롤링 해보자.
예로 Naver 배당주 페이지를 웹크롤링해보자.
※ 소스
<?php
require_once 'simple_html_dom.php';
$cnt = 0;
$fp = fopen("배당주.txt", 'w');
fwrite($fp, "[");
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)';
for($i = 1;$i < 27;$i++) {
$html ="";
$data["page"] = $i;
$url = 'https://finance.naver.com/sise/dividend_list.naver?field=dividend_rate&sosok=&ordering=desc&page=' . $i;
echo($url .'<br>');
$ch[$i] = curl_init(); //curl 초기화
curl_setopt($ch[$i], CURLOPT_URL, $url); //URL 지정하기
curl_setopt($ch[$i], CURLOPT_HTTPHEADER, array("Cache-Control: no-cache"));
curl_setopt ($ch[$i], CURLOPT_HEADER, 0);
curl_setopt ($ch[$i], CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch[$i], CURLOPT_POST, 0);
curl_setopt ($ch[$i], CURLOPT_USERAGENT, $agent);
curl_setopt ($ch[$i], CURLOPT_REFERER, "");
curl_setopt ($ch[$i], CURLOPT_TIMEOUT, 3);
$response[$i] = curl_exec($ch[$i]);
curl_close($ch[$i]);
//echo($response);
$html = str_get_html($response[$i]);
foreach( $html->find( 'table.type_1 tr td a' ) as $a ) {
$cnt ++;
if ($cnt > 1) {
fwrite($fp, ",");
//echo ',';
}
fwrite($fp, '["'
. str_replace("code=","",strstr($a->href,"code="))
. '","'
. iconv("EUC-KR", "UTF-8", $a->plaintext)
. '"]');
echo '{"code":"';
echo str_replace("code=","",strstr($a->href,"code="));
}
$html->clear();
}
fwrite($fp, "]");
fclose($fp);
?>
※ 실행
728x90
'Software > PHP' 카테고리의 다른 글
PHP 시작하기 - header 및 호출시 파라멘트 읽기 (0) | 2024.06.22 |
---|---|
phpmyadmin에서 SQL 내보내기 euc-kr 추가하기 (0) | 2024.06.21 |
PHP 보안관련 설정 (0) | 2024.05.25 |
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- QT
- plot
- Canvas
- 초중종분리
- web
- 미로
- JSON
- 포트 포워덩
- svg
- 웹크롤링
- 3d
- maze
- csv
- AI
- Selenium
- game
- MySQL
- png2ico
- PyQtGraph
- JavaScript
- Python
- Java
- 바둑판
- pyside6
- vscode
- c#
- MSX
- 디지털시계
- Winform
- php
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
글 보관함