테스트 환경 : CentOS 7 / MariaDB 10.1.12 / Python 3.5
1. BeautifulSoup
- BeautifulSoup를 이용하면 웹에서 사용하는 html 소스를 가져와서 필요한 데이터를 파싱하여 사용할 수 있다. (Python 3.5 환경에서는 Beatifulsoup4를 사용해야 하며 낮은 버전을 다운받을 경우 에러가 발생한다.)
[python@localhost ~]$ pip3.5 install BeautifulSoup4 Collecting BeautifulSoup Downloading BeautifulSoup-3.2.1.tar.gz
- 웹페이지 html 소스를 파일로 저장할 수 있다.
- BeautifulSoup을 이용해서 원하는 데이터를 파싱 후 데이터베이스에 저장(html 소스 내에 주소에 있는 종목코드와 종목명을 파싱)
import urllib
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://finance.naver.com/sise/sise_market_sum.nhn?sosok=0&page=1')
source = BeautifulSoup(html.read())
out = open('JS_html.txt','w')
print(source,file=out)
out.close
create table test.JS_INFO(JS_CD varchar(10), JS_NM varchar(100));
import urllib
import pymysql
from urllib.request import urlopen
from bs4 import BeautifulSoup
conn = pymysql.connect(host='192.168.219.153', port=3306, user='root', passwd='root', db='test',charset='utf8',autocommit=True)
cur = conn.cursor()
url = 'http://finance.naver.com/sise/sise_market_sum.nhn?sosok=0&page=1'
html = urlopen(url)
source = BeautifulSoup(html.read())
max_page=source.find_all("table",align="center")
mp = max_page[0].find_all("td",class_="pgRR")
mp_num = int(mp[0].a.get('href')[-2:])
for page in range(1, mp_num+1):
url = 'http://finance.naver.com/sise/sise_market_sum.nhn?sosok=0&page=' + str(page)
html = urlopen(url)
source = BeautifulSoup(html.read())
srlists=source.find_all('tr')
a = None
for i in range(1,len(srlists)-1):
if(srlists[i].a != a):
cur.execute("insert into JS_INFO values (%s, %s)", (srlists[i].a.get('href')[-6:],srlists[i].a.text))
- 각 페이지의 html 소스에서 <tr></tr> 을 기준으로 데이터를 자른다.
- 자른 부분마다 href에 있는 데이터(주소)에서 종목코드를 가져오고, 종목명을 가져온다.'Programming' 카테고리의 다른 글
| [Python]주식 종목 데이터 및 일별 시세 데이터 DB적재 (0) | 2016.04.22 |
|---|---|
| Python Parallel로 DB 데이터 읽어오기 (0) | 2016.04.18 |
| Python Parallel 예제 소스 분석 (0) | 2016.04.17 |
| Python Parallel 설치하기 (0) | 2016.04.17 |
| 종목의 데이터 추출하기 (0) | 2016.04.14 |