본문 바로가기
kipfa 필기

0807_python을 이용한 네이버 뉴스 webcrawling 예제 코드

by 헤옹스 2017. 8. 7.

http://itissmart.tistory.com/19#recentEntries

 

 

<소스 코드>

 

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'http://news.naver.com'
response = urlopen(url)
plain_text = response.read().decode('euc-kr')
soup = BeautifulSoup(plain_text, 'html.parser')

#step 1)
#print(plain_text)
#print(soup)
#위 두개 명령어는 출력결과가 크게 달라보이지 않음.

#step 2)
#print(soup.find('a'))
#소스에서 가장 첫번째 a태그 출력.

#step 3)
#print(soup.find_all('a'))
#찾고자 하는 대상 전부를 찾아 출력.(결과를 자동으로 배열에 넣어서 돌려줌.)

#step 4)
#lists = soup.find_all('a')
#for list in lists:
#    print(list)
#한줄에 하나씩 정렬이 되어 출력.

#step 5)
#lists = soup.find_all('div', class_='newsnow_tx_inner')
#for list in lists:
#    print(list.find('a'))
#'이시각 주요뉴스' 부분은 class='newsnow_tx_inner'인 div태그에 포함된다는 것을 찾아 출력.

#step 6)
#lists = soup.find_all('div', class_='newsnow_tx_inner')
#for list in lists:
#    print(list.find('a').find('strong').text + " " + list.find('a').get('href'))
#드디어 뉴스 헤드라인과 URL정보를 분리해냄!!


#파이썬의 파일 I/O 처리를 추가한다면 크롤링 결과를 txt파일로 생성할 수도 있고,
#database 연결을 통해 정보를 축적해서 활용하는 작업도 얼마든지 가능합니다.


#출처: http://itissmart.tistory.com/19#recentEntries [IT is Smart]

 

 

 

<실행결과>

 

 

<소스코드>

 

** 헤더파일의 from urllib.request 와 from bs4를 실행하기 위해 cmd창에서 install하는 작업을 거쳐야함.

블로그에는

BeautifulSoap은 아래에서 다운로드 받아서 설치할 수 있습니다. 

https://www.crummy.com/software/BeautifulSoup/


라고 소개되어있지만(사이트에서 .tar.gz 형식의 해당 파일을 다운로드 받아서 직접 압축해제하고... 정녕 이래야함????!!  ;.;....)

교수님이 cmd창에서 바로 설치하는 법 알려주셔땅!!!!

 

 

 

 

 


<용도>

원하는 컨텐츠가 남을때까지 크롤링하여 작업하기!!

페이지 사이트에서 제공해주는 데에만 한정되어 있는 Open API.

Open API로 제공해주지 않아도 내가 원하는 정보 얻을 수 있음ㅎㅎ

 

-> DB에 크롤링한 정보를 저장하겠지.

 

 

'kipfa 필기' 카테고리의 다른 글

0807_Controlling Arduino With Python Based Web API (No Php) 2  (0) 2017.08.07
0806_Controlling Arduino With Python Based Web API (No Php) 1  (0) 2017.08.07
0728  (0) 2017.07.28
0727 오후  (0) 2017.07.27
0727 오전  (0) 2017.07.27