티스토리 뷰
웹 크롤링 이용하기
0. 웹크롤링 이란?
- 웹 긁어오는 것.
- 웹 스크래치, 웹 파싱 이라고도 불림.
1. 스크레치 어떻게 하는가?
- NodeJS
- 긁어오기 : request모듈, restler 모듈 등등
- 가공하기 : cheerio 모듈
- Python
- 긁어오기 : requests 모듈
- 가공하기 : BeautifulSoup
- NodeJS 샘플
rest.post("https://XXXXXXXXXX", {
data: {
Name: "Jang"
}
}).on('complete', function(body) {
console.log(body);
$ = cheerio.load(body);
});
2. 스크레치 어떻게 하는가? (고급기능)
- 위와 같은(1번) 방법으로 잘안될 때 보면 대부분은 헤더값으로 보안처리를 한다.
- 헤더값도 포함해서 보내기.
- 개발자도구 (F12) Network > Reqeust Headers 확인 (크롬 기준)
- NodeJS 변경된 샘플
rest.post("https://XXXXXXXXXX", {
data: {
Name: "Jang"
},
headers: {
Host:"XXXXXXXXXX",
Referer: "https://XXXXXXXXXX",
Cookie:"_ga=GA1.3.2077401677.1461896571; connect.sid=s%3AtJVqH73Na63HIifXX7ZIU8sq.RBpgAM%2FxGcSapsi6Xd0qjVonUqQUQV4BYnI0CmhA%2F9U",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36"
}
}).on('complete', function(body) {
console.log(body);
$ = cheerio.load(body);
});
3. 어떻게 가공하는가?
- 위에 소개한 BeautifulSoup이나 cheerio은 기본은 같다.
- CSS 선택자 or jquery의 선택자 와 같다.
- 소스 적용전 크롤링하는 사이트 웹에서 확인하기.
- Jquery가 사용되는경우
- jquey 문법과 같음으로 미리 콘솔로 확인하면 된다.
- Jquery가 사용되지 않는 경우
var body = document.getElementsByTagName("body");
var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-1.12.3.min.js";
body[0].appendChild(script)
- 위 소스 추가 후 이용.
- 선택자 이용법
- 돔 (div, tr ... )
- id : #
- class : .
- attr : []
- 바로아래자식돔 ( tr > td )
- 메서드
- $("div").text() : 텍스트 가져오기
- $("div").html() : HTML 가져오기
- $("div").attr() : 속성 가져오기
4. 샘플 코드
- Node 와 Python 같은 소스.
- URL : http://developer.achusoft.co.kr/eco_test.html
- NodeJS 샘플
var cheerio = require('cheerio');
var rest = require("restler");
rest.get("http://developer.achusoft.co.kr/eco_test.html", {})
.on('complete', function(body) {
$ = cheerio.load(body);
var arr = [];
var arrTitle = [];
$(".eco-table thead tr th").each(function() {
arrTitle.push($(this).text().trim());
});
$(".eco-table tbody tr").each(function() {
var item = {};
$(this).find("td").each(function(i) {
item[arrTitle[i]] = $(this).text().trim();
})
arr.push(item);
});
console.log(arr);
});
- Python
#-*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import json
if __name__ == "__main__":
r = requests.get("http://developer.achusoft.co.kr/eco_test.html", headers={})
soup = BeautifulSoup(r.text, "lxml")
arr = []
arrTitle = [];
for th in soup.find("table", {'class':'eco-table'}).find('thead').findAll("th"):
arrTitle.append(th.get_text(strip=True))
for tr in soup.find("table", {'class':'eco-table'}).find('tbody').findAll("tr"):
i = 0
item = {}
for td in tr.findAll("td"):
item[arrTitle[i]] = td.get_text(strip=True)
i = i + 1
arr.append(item)
print json.dumps(arr, ensure_ascii=False)
5. EUC-KR -> UTF-8
- NodeJS는 기본적으로 utf-8을 이용.
- euc-kr 사이트 크롤링하기.
- iconv 이용
- 바로 하면 안되고 버퍼에 담아서 해야 된다!
var Iconv = require('iconv').Iconv;
var iconv = new Iconv('euc-kr', 'utf-8');
rest.get("http://EUCKR-HOMEPAGE", {
encoding: 'binary',
decoding: 'binary'
}).on('complete', function(body) {
var searchResultBin = new Buffer(body, 'binary');
var searchResultUtf8 = iconv.convert(searchResultBin).toString('utf-8');
$ = cheerio.load(searchResultUtf8);
});
6. 마무리
- 당신은 이제 모든사이트를 가져올수 있고 컨트롤 가능하다.
- 하지만 무단으로 가져오면 처벌받을 수 있으니.. 잘하자.
'NODEJS' 카테고리의 다른 글
pm2 이용하기 (1) | 2016.02.26 |
---|---|
NODEJS 설치하기 (0) | 2016.02.18 |
- Total
- Today
- Yesterday
- 봇
- 엘라스틱서치 백업
- 2FA
- mqtt
- AmazonMQ
- electron-updater
- 2factor
- AWS
- real
- maria
- 브라우저 제어
- 팀룸
- 오픈API
- MariaDB Galera
- auto update
- 엘라스틱서치 복구
- elasticsearch mapping change
- 브라우저봇
- ElasticSearch
- 마리아
- puppeteer
- activemq
- electron
- Redis
- elasticsearch mapping
- 자동업데이트
- backup
- 네이트온
- Restore
- bitbucket
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |