Skip to content

Commit 8c176d1

Browse files
committed
Working setup.py init
0 parents  commit 8c176d1

12 files changed

Lines changed: 361 additions & 0 deletions

File tree

‎bigpython/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from . import office, webscrap
2+
print('{} imported'.format(__name__))

‎bigpython/office/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .word import Word
2+
from .excel import Excel

‎bigpython/office/excel.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import pandas as pd
2+
3+
def Excel(io, sheetname=None, header=0):
4+
frames = pd.read_excel(io, sheetname=sheetname, header=header)
5+
frames = [(sheetname, frame) for sheetname, frame in frames.items()]
6+
return frames[0][1] if len(frames) == 1 else frames

‎bigpython/office/word.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import docx
2+
import pandas as pd
3+
from .excel import Excel
4+
import types
5+
6+
def Word(filepath_or_buffer=None):
7+
"""
8+
Extends docx.document.Document
9+
"""
10+
# patch class
11+
docx.document.Document.extract_text = extract_text
12+
docx.document.Document.extract_tables = extract_tables
13+
docx.document.Document.tables_to_excel = tables_to_excel
14+
docx.document.Document.add_tables_from_excel = add_tables_from_excel
15+
docx.document.Document.add_picture = add_picture
16+
17+
# make instance using patched class
18+
doc = docx.Document(filepath_or_buffer)
19+
20+
return doc
21+
22+
def extract_text(self):
23+
return '\n'.join([p.text for p in self.paragraphs])
24+
25+
def extract_tables(self):
26+
table_list = []
27+
for table in self.tables:
28+
table_data = []
29+
for row in table.rows:
30+
row_data = []
31+
for cell in row.cells:
32+
cell_text = ''
33+
for p in cell.paragraphs:
34+
cell_text += p.text
35+
# if debug:
36+
# print(cell_text, end=' ')
37+
row_data.append(cell_text)
38+
# if debug:
39+
# print()
40+
table_data.append(row_data)
41+
42+
try:
43+
import pandas as pd
44+
table_frame = pd.DataFrame(table_data)
45+
table_list.append(table_frame)
46+
except ImportError:
47+
# TODO: pandas가 없는 경우 텍스트로 출력
48+
pass
49+
50+
return table_list[0] if len(table_list) == 1 else table_list
51+
52+
def tables_to_excel(self, filepath_or_buffer):
53+
table_list = self.extract_tables()
54+
55+
excel_file = pd.ExcelWriter(filepath_or_buffer)
56+
for i, table_frame in enumerate(table_list):
57+
table_frame.to_excel(excel_file, 'Sheet{}'.format(i+1))
58+
excel_file.save()
59+
60+
return filepath_or_buffer
61+
62+
def add_tables_from_excel(self, excel_filepath, sheetname=None,
63+
table_style='TableGrid'):
64+
table_frames = Excel(excel_filepath, sheetname=sheetname)
65+
66+
if not isinstance(table_frames, list):
67+
table_frames = [table_frames]
68+
69+
for frame in table_frames:
70+
frame = frame.fillna('')
71+
nrows, ncols = len(frame), len(frame.columns)
72+
table = self.add_table(rows=nrows, cols=ncols, style='TableGrid')
73+
# table.style = 'LightShading-Accent1'
74+
for i, row in enumerate(table.rows):
75+
for j, cell in enumerate(row.cells):
76+
cell.text = str(frame.iloc[i, j])
77+
78+
def add_picture(self, image_path_or_stream, width=None, height=None):
79+
if width: width = docx.shared.Inches(width)
80+
if height: height = docx.shared.Inches(height)
81+
82+
run = self.add_paragraph().add_run()
83+
return run.add_picture(image_path_or_stream, width, height)

‎bigpython/webscrap/__init__.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# coding: utf-8
2+
from . import io, html
3+
4+
import pip
5+
import platform, sys, os, stat, zipfile
6+
import requests
7+
import time
8+
9+
def get_browser(browser='Chrome', driverpath=None):
10+
driver_map = {'Chrome': 'chromedriver'}
11+
12+
try:
13+
from selenium import webdriver
14+
except ImportError:
15+
setup_webdriver()
16+
try:
17+
from selenium import webdriver
18+
except:
19+
raise
20+
else:
21+
if driverpath is None:
22+
driverpath = os.path.join('.', driver_map[browser])
23+
driver = getattr(webdriver, browser)(driverpath)
24+
return driver
25+
26+
27+
def setup_webdriver():
28+
# selenium package 설치
29+
pip.main(['install', 'selenium'])
30+
31+
print('chromedriver 다운로드')
32+
downloaded_file = download_chromedriver()
33+
print(downloaded_file)
34+
35+
# 압축 해제
36+
print('다운로드 받은 파일 압축 해제 ...')
37+
driverzip = zipfile.ZipFile(downloaded_file)
38+
driverzip.extractall()
39+
driverfile = driverzip.namelist()[0]
40+
driverzip.close()
41+
42+
# 실행권한 설정
43+
st = os.stat(driverfile)
44+
os.chmod(driverfile, st.st_mode | stat.S_IEXEC)
45+
46+
print('설정 테스트 ...', end=' ')
47+
test_webdriver(driverfile)
48+
print('완료')
49+
50+
def download_chromedriver():
51+
driverfile_map = {'Windows': 'chromedriver_win32.zip',
52+
'Darwin': 'chromedriver_mac32.zip'}
53+
download_target = driverfile_map.get(platform.system(), None)
54+
if download_target is None:
55+
sys.exit('No chromedriver for {0}'.format(platform.system()))
56+
57+
chromedriver_url = 'http://chromedriver.storage.googleapis.com/2.22/'
58+
chromedriver_url = chromedriver_url + download_target
59+
60+
driverfilepath = http_download(chromedriver_url, download_target)
61+
return driverfilepath
62+
63+
def test_webdriver(driverfile):
64+
from selenium import webdriver
65+
chrome = webdriver.Chrome(os.path.join('.',driverfile))
66+
chrome.get('http://www.gogle.com')
67+
time.sleep(5)
68+
search_box = chrome.find_element_by_name('q')
69+
search_box.send_keys('파이썬')
70+
time.sleep(5)
71+
search_box.submit()
72+
time.sleep(10)
73+
chrome.quit()
74+
75+
def http_download(url, 파일경로):
76+
응답 = requests.get(url)
77+
if os.path.exists(파일경로):
78+
print('File already exists')
79+
return 파일경로
80+
81+
with open(파일경로, 'wb') as 파일:
82+
for 조각 in 응답.iter_content(100000):
83+
파일.write(조각)
84+
85+
return 파일경로
86+
87+
if __name__ == '__main__':
88+
setup_webdriver()

‎bigpython/webscrap/crawler.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from random import seed, choice
2+
from . import html
3+
4+
5+
def get_internal_links(url):
6+
soup = html.get_soup(url)
7+
8+
"""Retrieves a list of all internal links in html"""
9+
pass
10+
11+
def get_external_links(url):
12+
soup = html.get_soup(url)
13+
"""retrieves a list of all external links in html"""
14+
pass
15+
16+
def get_random_link(url, where='internal'):
17+
get_link = {'internal': get_internal_links,
18+
'external': get_external_links}
19+
20+
link_list = get_link[where]
21+
# return a random link if there is any
22+
return choice(link_list) if list_list else []

‎bigpython/webscrap/html.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# coding: utf-8
2+
from urllib.parse import urlparse
3+
import re
4+
import pandas as pd
5+
from bs4 import BeautifulSoup
6+
import importlib
7+
from . import io
8+
9+
def get_soup(src, encoding='utf-8'):
10+
"""Returns BeautifulSoup from URL or file
11+
12+
src: url or filepath
13+
encoding: (default=utf-8)
14+
"""
15+
# check if url or filepath
16+
scheme = urlparse(src).scheme
17+
if re.compile('(http|https)').match(scheme):
18+
res = io.http_download(src)
19+
doc = res.text
20+
else:
21+
doc = open(src, encoding=encoding)
22+
23+
# select parser for BeautifulSoup
24+
parser = 'lxml' if importlib.find_loader('lxml') else 'html.parser'
25+
return BeautifulSoup(doc, parser)
26+
27+
def extract_tables(table_elements):
28+
table_frames = pd.read_html(str(table_elements))
29+
return table_frames

‎bigpython/webscrap/html_test.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# coding: utf-8
2+
from . import io
3+
from . import html
4+
from bs4 import BeautifulSoup
5+
import os
6+
7+
def test_extract_table():
8+
url = 'https://ko.wikipedia.org/wiki/%EC%95%A8%EB%9F%B0_%ED%8A%9C%EB%A7%81'
9+
filename = io.snapshot_webpage(url, 'turing_wiki.html')
10+
with open(filename) as f:
11+
soup = BeautifulSoup(f, 'html.parser')
12+
# 파일 삭제
13+
os.unlink(filename)
14+
15+
tables = soup.select('table.wikitable')
16+
17+
table_frames = html.extract_tables(tables)
18+
assert table_frames[0].ix[0,0] == '1912년'
19+
20+
def test_get_soup():
21+
# source is url
22+
url = 'https://ko.wikipedia.org/wiki/%EC%95%A8%EB%9F%B0_%ED%8A%9C%EB%A7%81'
23+
soup = html.get_soup(url)
24+
assert soup.title.text == "앨런 튜링 - 위키백과, 우리 모두의 백과사전"
25+
26+
# source is file
27+
filename = io.snapshot_webpage(url, 'turing_wiki.html')
28+
soup = html.get_soup(filename)
29+
# 파일 삭제
30+
os.unlink(filename)
31+
32+
assert soup.title.text == "앨런 튜링 - 위키백과, 우리 모두의 백과사전"

‎bigpython/webscrap/io.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import sys
2+
from urllib.parse import urlparse, unquote, unquote_plus
3+
import requests
4+
5+
def snapshot_webpage(url, filename=None, mode='wb', data=None):
6+
res = http_download(url, data=data)
7+
8+
# 파일명 설정
9+
if filename is None:
10+
path = urlparse(url).path
11+
path = unquote_url(path)
12+
filename = os.path.basename(path)
13+
14+
# 파일로 저장
15+
with open(filename, mode) as f:
16+
if mode[-1] == 'b':
17+
for chunk in res.iter_content(100000):
18+
f.write(chunk)
19+
else:
20+
f.write(res.text)
21+
22+
return filename
23+
24+
def http_download(url, method='get', data=None):
25+
if method == 'get':
26+
res = requests.get(url, params=data)
27+
res.raise_for_status()
28+
return res
29+
30+
def unquote_url(url):
31+
if '+' in url:
32+
return unquote_plus(url)
33+
return unquote(url)

‎bigpython/webscrap/io_test.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# coding: utf-8
2+
from . import io
3+
import pytest
4+
import requests
5+
import os
6+
from urllib.parse import quote_plus
7+
8+
def test_http_download():
9+
res = io.http_download('http://google.com')
10+
assert res.status_code == 200
11+
12+
with pytest.raises(requests.ConnectionError):
13+
io.http_download('http://no-such-domain.com')
14+
15+
with pytest.raises(requests.HTTPError):
16+
io.http_download('http://google.com/nosuchpath')
17+
18+
def test_unquote_url():
19+
url = 'https://ko.wikipedia.org/wiki/%EC%95%A8%EB%9F%B0_%ED%8A%9C%EB%A7%81'
20+
url_unquoted = io.unquote_url(url)
21+
basename = os.path.basename(url_unquoted)
22+
assert basename == '앨런_튜링'
23+
24+
url_quote_plus = quote_plus(url_unquoted)
25+
url_unquoted = io.unquote_url(url_quote_plus)
26+
basename = os.path.basename(url_unquoted)
27+
assert basename == '앨런_튜링'
28+
29+
def test_snapshot_webpage():
30+
url = 'https://ko.wikipedia.org/wiki/%EC%95%A8%EB%9F%B0_%ED%8A%9C%EB%A7%81'
31+
filename = io.snapshot_webpage(url, '앨런튜링_위키.html')
32+
assert os.path.exists(filename)
33+
# cleanup
34+
os.unlink(filename)
35+
36+
with pytest.raises(requests.ConnectionError):
37+
io.snapshot_webpage('http://no-such-domain.com', 'no.html')
38+
39+
with pytest.raises(requests.HTTPError):
40+
io.http_download('http://google.com/nosuchpath')

0 commit comments

Comments
 (0)