티스토리 뷰
java를 통해 크롤링 할 땐 일반적으로 jsoup이 사용된다.
이 포스팅에서는 jsoup의 select 메소드를 사용해서 parsing 하는 과정을 정규식을 사용한 방법으로 고쳐보았다.
크롤링 해오는 컨텐츠는 네이버 블로그이다.
- jsoup을 사용한 코드
- 특징
- 간결하고 간편하다.
- 실행시간: 3.077초 대략 3~5초 사이로 나타났다.
- 특징
long start = System.currentTimeMillis();
String str = "";
ArrayList list = new ArrayList();
for(int j = 0 ; j < 10 ; j++) { // 10 페이지까지 크롤링
String url = "https://search.naver.com/search.naver?date_from=&date_option=0&date_to=&dup_remove=1&nso=&post_blogurl=&post_blogurl_without=&query="+enc_query+"&sm=tab_pge&srchby=all&st=sim&where=post&start="+j+"1";
try {
Document doc = Jsoup.connect(url).get();
Element container = doc.select("#container").first();
Elements content_all = container.select(".sh_blog_top");
for(int i = 0; i < content_all.size(); i++) {
HashMap map = new HashMap();
Element content = content_all.get(i);
Element thumb_divs = content.select(".thumb").first();
// 썸네일 이미지
String thumb_nail = thumb_divs.select("img").attr("src");
map.put("thumb_nail", thumb_nail);
// 게시물 링크
String link = thumb_divs.select("a").attr("href");
map.put("link", link);
// 게시물 등록일
Element regdate = content.select(".txt_inline").first();
map.put("regdate", regdate.text());
// 게시물 제목
Element title = content.select(".sh_blog_title").first();
map.put("title", title.text());
// 게시물 내용
Element passage = content.select(".sh_blog_passage").first();
map.put("passage", passage.text());
// 블로그 제목
Element blog_name = content.select(".txt84").first();
map.put("blog_name", blog_name.text());
// 블로그 링크
Element blog_url = content_all.select(".url").first();
map.put("blog_url", blog_url.text());
list.add(map);
}
} catch(Exception e) {
e.printStackTrace();
}
}
ObjectMapper mapper = new ObjectMapper();
try {
str = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("실행시간: "+(end - start )/1000.0 +"초");
// 3.037초
- 정규식을 사용해서 select하는 코드
- Document로 받아온 것을 Element화 하는 것 까지는 코드가 비슷하다
- 특징
- 정규식을 사용해서 parsing 하면서 코드가 길어졌다.
- 정규식을 사용하여 가독성이 다소 낮다.
- 실행시간: 2.774초, 3초를 넘지 않음
- jsoup을 사용한 것에 비해서는 빠르다.
long start = System.currentTimeMillis();
String str = "";
ArrayList list = new ArrayList();
for(int j = 0 ; j < 10 ; j++) { // 10 페이지까지 크롤링
String url = "https://search.naver.com/search.naver?date_from=&date_option=0&date_to=&dup_remove=1&nso=&post_blogurl=&post_blogurl_without=&query="+enc_query+"&sm=tab_pge&srchby=all&st=sim&where=post&start="+j+"1";
try {
Document doc = Jsoup.connect(url).get();
Element container = doc.select("#container").first();
Elements content_all = container.select(".sh_blog_top");
for(int i = 0; i < content_all.size(); i++) {
HashMap map = new HashMap();
Element thumb = content_all.get(i);
String blog_li = thumb.toString().replace('"', ' ');
blog_li = blog_li.replaceAll("(\r\n|\r|\n|\n\r)", "");
// 썸네일 이미지
Pattern patn = Pattern.compile("<.*?src=(.*?)alt.*?>");
Matcher matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("thumb_nail", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
// 게시물 링크
patn = Pattern.compile("<a.*?href=(.*?)target.*?sp_thmb.*?>");
matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("link", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
// 게시물 등록일
patn = Pattern.compile(".*?txt_inline.*?>(.*?)<");
matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("regdate", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
// 게시물 제목
patn = Pattern.compile(".*?sh_blog_title.*?>(.*?)</a>");
matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("title", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
// 게시물 내용
patn = Pattern.compile(".*?sh_blog_passage.*?>(.*?)</dd>");
matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("passage", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
// 블로그 제목
patn = Pattern.compile(".*?txt84.*?>(.*?)</a>");
matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("blog_name", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
// 블로그 링크
patn = Pattern.compile(".*?class= url.*?>(.*?)</a>");
matr = patn.matcher(blog_li);
while(matr.find()) {
map.put("blog_url", matr.group(1));
if(matr.group(1) == null) {
break;
}
}
list.add(map);
}
} catch(Exception e) {
e.printStackTrace();
}
}
ObjectMapper mapper = new ObjectMapper();
try {
str = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("실행시간: "+(end - start )/1000.0 +"초");
// 실행시간: 2.774초
- 결론
- 정규식은 속도가 빠르고 원하는대 로 데이터를 가공하는 것이 더 용이했으나 코드가 더 길어졌고 가독성이 떨어져서 주석이 꼭 필요할 것 같다.?
'web crawling' 카테고리의 다른 글
웹크롤링 robots.txt (0) | 2020.01.18 |
---|---|
selenium 속도문제 url 직접연결, multiprocessing (0) | 2020.01.18 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 클래스
- 배열
- C++
- server side rendering
- 동적프로그래밍
- 재귀함수
- javascript
- 구조체
- 스텍
- 소프트웨어
- 운영체제
- C
- 이진탐색
- 알고리즘
- stackframe
- 인접리스트
- Stack
- react
- 자료구조
- BFS
- 퀵정렬
- 병행프로세스
- 세마포어
- 최단경로
- client side rendering
- Java
- dfs
- 인접행렬
- 교착상태
- 입출력장치
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함