인터넷만 연결되어있다면 일정한 시간간격으로 크롤러를 해와서 정보를 띄워주는 GUI를 만들어보았다.

 

 

더보기
 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import sys
import numpy as N
 
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import QTimer, QTime
import requests
from bs4 import BeautifulSoup
 
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
 
form_class = uic.loadUiType("untitled2.ui")[0]
 
 
html = req.text
soup = BeautifulSoup(html, 'html.parser')
cnt = 0
class MyWindow(QDialog, form_class):
   
   def __init__(self):
       super().__init__()
       self.setupUi(self)
       # QTimer => 이벤트루프에 변수 timer라는 타이머 등록 
       self.timer = QTimer(self)
       # 1000(1sec)*x 단위로 이벤트루프 진입시(exec_()) 타이머시작
       self.timer.start(1500*1)
       # 타이머 지정 시간마다 이벤트발생 -> connect 를 통해 임의의 timeout def 슬롯 연결
 
       # crawling 을 갱신하기 위한 타이머
       self.timer_crawler = QTimer(self)
       self.timer_crawler.start(1000*60*5)
       self.timer_crawler.timeout.connect(self.timeout_crawler)
 
   def timeout(self):
       # globar => 전역변수를 지역범위에서 사용하기위해
       global cnt
       self.textEdit.setText(result[cnt].text)
       self.textEdit_2.setText(result[cnt+1].text)
       self.textEdit_3.setText(result[cnt+2].text)
       cnt = cnt+3
       if(cnt > 20): cnt = 0
 
   def timeout_crawler(self):
       req = requests.get(url)
       html = req.text
       soup = BeautifulSoup(html, 'html.parser')
       result = soup.select('strong.news-tl > a')
 
if __name__ == "__main__":
   app = QApplication(sys.argv)
   myWindow = MyWindow()
 
   app.exec_()
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

'python > crawler' 카테고리의 다른 글

BeautifulSoup 를 이용한 크롤러 - Junnnho  (0) 2019.11.14

(본 글은 window 사용자를 기준으로 작성되었습니다.)

 

본인이 원하는 웹사이트에서 필요한 정보를 긁어오는 crawler 를 공부해보자

python, nodeJs 두개의 언어로 크롤러를 해봤는데 개인적인 경험으로는 python 코드가 더 직관적이고 쉬운 것 같다.

크롤러를 위해 설치할 라이브러리는 beautifulsoup4 와 requests 이다.

 

설치

pip install beautifulsoup4 (라이브러리)

pip install requests (웹 객체 사용을 위함)

 

설명

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
32
33
from bs4 import BeautifulSoup
# beautifulsoup import
import requests
# requests -> 웹 객체(html)를 편하게 사용하기 위한 http requests 라이브러리
import sys
 
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
# 크롤러를 성공적으로 해오게 되면 글자가 깨지는 경우가 발생한다.
# 이를 위해서 따로 선언해줘야한다
 
# url = '크롤러를 원하는 페이지'
# requests 모듈을 이용하여 url 의 객체를 받아옴
 
html = req.text
# 받아온 객체 req 에 대한 text = code 를 가져옴
soup = BeautifulSoup(html, 'html.parser')
# BeautifulSoup은 html 코드를 Python이 이해하는 객체 구조로 변환하는
# Parsing 역할을 함
# BeautifulSoup를 이용해 원하는 형식의 정보를 추출
 
# 원하는 url에서 F12 -> Elements 탭에 들어가면
# 현재 보고있는 페이지가 어떤 형식으로 되어있는지 소스마다 체크가 가능하다.
# 반환형태는 array형태
 
for res in result:
    print(res.text)
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

select 태그 설명 (find보다 오류도 없고 간단하다)

연합뉴스/it/all 의 url 을 기준 헤드라인만 따와보자

F12 -> Elements(요소검사) 를 통해 헤드라인을 구현한 코드를 찾는다.

select 사용법

soup.select('원하는 정보')

soup.select('태그명')

soup.select('.클래스명')

soup.select('상위태그명 > 하위태그명 > 하위태그명')

soup.select('상위태그명.클래스명 > 하위태그명.클래스명') # 바로 아래의(자식) 태그를 선택시에는 > 기호를 사용 soup.select('상위태그명.클래스명 하위태그명') # 아래의(자손) 태그를 선택시에는 띄어쓰기 사용

soup.select('상위태그명 > 바로아래태그명 하위태그명')

soup.select('#아이디명')

soup.select('태그명.클래스명)

soup.select('#아이디명 > 태그명.클래스명)

이런식으로 원하는 위치를 상위 > .. > 하위 순으로 찾아나가면 된다.

 

당장 보이는 허성무 창원시장, 미국.... 은 strong 클래스(이름 : new-tl) 의 하위 a태그에 위치함으로

strong.new-tl > a 로 간단하게 헤드라인을 가져올 수 있다.

 

끗.

'python > crawler' 카테고리의 다른 글

로컬기반 크롤러 프로그램  (0) 2019.11.14

+ Recent posts