반응형

네이버에서 환율 정보를 scraping 하고 IFTTT를 이용해 SMS로 보낸다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from bs4 import BeautifulSoup as bs
import urllib.request as req
import requests
 
url = 'https://finance.naver.com/marketindex/' # 시장지표: 네이버 금융
res = req.urlopen(url)
 
soup = bs(res, 'html.parser')
title = soup.select_one('a.head > h3.h_lst').string
rate = soup.select_one('div.head_info > span.value').string
 
# IFTTT Platform
# To trigger an Event make a POST or GET web request to:
trigger_url = 'https://maker.ifttt.com/trigger/이벤트_입력/with/key/키_입력'
# With an optional JSON body of:
result = requests.post(trigger_url, data = { "value1" : title, "value2" : rate, "value3" : 'Sean' })
# The data is completely optional, and you can also pass value1, value2, and value3 as query parameters
# or form variables. This content will be passed on to the Action in your Recipe.
print('Result:', result, result.status_code, result.reason)
 

 

 

 

 

 

 

 

 

반응형

'Machine Learning' 카테고리의 다른 글

[Scraping] 환율 정보  (0) 2024.01.02
OCR with Tesseract on Windows - Windows에서 테서랙트 사용하기  (0) 2020.10.07
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
:
반응형

 환율 정보를 스크랩 해 보자.

 

네이버 환율 정보다.

 

크롬에서 F12를 누르면 위와 같은 정보가 표시된다. 정보를 태그와 클래스명으로 구분할 수 있을거 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import urllib.request
from bs4 import BeautifulSoup as bs
 
url = "https://m.stock.naver.com/marketindex/home/exchangeRate/exchange"
with urllib.request.urlopen(url) as response:
    html = response.read().decode('utf-8')
 
soup = bs(html, 'html.parser')
 
all_countries = soup.find_all('strong''MainListItem_name__2Nl6J')
all_rates = soup.find_all('span''MainListItem_price__dP8R6')
 
for country, rate in zip(all_countries, all_rates):
    print(country.string + ': ', rate.string)
 
#for i, c in enumerate(all_countries):
#    print(i+1, c.string)
 
#for i, r in enumerate(all_rates):
#    print(i+1, r.string)
 
#print(soup.find('strong', 'MainListItem_name__2Nl6J').string)
#print(soup.find('span', 'MainListItem_price__dP8R6').string)
 

 

같은 클래스명을 쓰는 정보가 여러개 있다. 모두 검색하여 표시한다.

 

환율 정보가 잘 표시된다.

 

반응형

'Machine Learning' 카테고리의 다른 글

[Scraping] 환율 정보를 SMS로 보내기  (3) 2024.01.02
OCR with Tesseract on Windows - Windows에서 테서랙트 사용하기  (0) 2020.10.07
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
:
반응형

광학 문자 인식(Optical Character Recognition; OCR)은 사람이 쓰거나 기계로 인쇄한 문자의 영상이나 이미지를 기계가 읽을 수 있는 문자로 변환하는 것이다. 다양한 운영체제를 위한 광학 문자 인식 엔진 Tesseract를 윈도우즈에서 사용해 보자.


Tesseract Windows version을 제공하는 UB Mannheim에 접속해서 적당한 플랫폼의 Tesseract를 다운 받는다.


설치한다.







Additional language data (download)를 클릭한다.


Korean을 선택한다.











Python-tesseract(pytesseract)를 설치한다. Python-tesseract은 Google의 Tesseract-OCR Engine의 wrapper이다.


영문 이미지를 준비한다.



한글 이미지를 준비한다.


1
2
3
4
5
6
7
from PIL import Image
import pytesseract
 
pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract'
 
print(pytesseract.image_to_string(Image.open('English.png')))
#print(pytesseract.image_to_string(Image.open('Korean.png'), lang = 'kor'))


영문, 한글 이미지를 읽고 텍스트를 출력한다.


영문 이미지 결과.


한글 이미지 결과.



Console에서 아래 명령어로도 같은 결과를 얻을 수 있다.

tesseract English.png stdout


tesseract Korean.png stdout -l kor


stdout이 아닌 다른 이름으로 출력을 지정하면 그 이름의 텍스트 파일로 출력된다.

tesseract English.png result


반응형

'Machine Learning' 카테고리의 다른 글

[Scraping] 환율 정보를 SMS로 보내기  (3) 2024.01.02
[Scraping] 환율 정보  (0) 2024.01.02
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
:

CSV 분석

Machine Learning 2019. 1. 20. 12:48 |
반응형

Python 기본 라이브러리 csv를 이용해 CSV(comma-separated values) 형식을 분석 할 수 있다.


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
import locale
import csv
 
lo = locale.getdefaultlocale()
# Tries to determine the default locale settings and returns them as a tuple of
# the form (language code, encoding).
print("Default language code: " + lo[0], "Default encoding: " + lo[1], sep = "\n", end = "\n\n")
 
filename = "list.csv"
with open(filename, "rt", encoding="euc_kr") as f:
    csv_data = f.read()
 
data = []
rows = csv_data.split("\n")
for row in rows:
    if row == "":
        continue
    cells = row.split(",")
    data.append(cells)
 
for c in data:
    print("%-8s %8s" %(c[1], c[2]))
 
print()
 
#Python csv library
with open(filename, "at", encoding="euc_kr") as f:
    # 'a' - open for writing, appending to the end of the file if it exists
    # For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes.
    # 'r+b' opens the file without truncation.
    csv_writer = csv.writer(f, delimiter = ",", quotechar = '"')
    csv_writer.writerow(["101""Math""4300"])
    csv_writer.writerow(["102""Physics""4800"])    
    csv_writer.writerow(["103""English""5700"])
# stream position을 바꾸고 싶으면 io module의 seek()을 f.seek(...)처럼 사용 한다.
# seek(offset[, whence])
# Change the stream position to the given byte offset. offset is interpreted relative to the
# position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
# SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
# SEEK_CUR or 1 – current stream position; offset may be negative
# SEEK_END or 2 – end of the stream; offset is usually negative
# Return the new absolute position.
 
with open(filename, "rt", encoding="euc_kr") as f:
    csv_reader = csv.reader(f, delimiter = ",", quotechar = '"')
    for cells in csv_reader:
        if cells == []:
            continue
        print("%-8s %8s" %(cells[1], cells[2]))
cs




list.csv:


결과:


실행 후 list.csv:



반응형
Posted by J-sean
:

JSON 분석

Machine Learning 2019. 1. 18. 20:14 |
반응형

Python 기본 라이브러리 json을 이용해 JSON (JavaScript Object Notation) 형식을 분석할 수 있다.


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
import urllib.request as req
import os.path
import json
 
url = "https://api.github.com/repositories"
filename = "repositories.json"
 
if not os.path.exists(filename):
    #req.urlretrieve(url, filename)
    # Legacy interface. It might become deprecated at some point in the future.
    with req.urlopen(url) as contents:
        jsn = contents.read().decode("utf-8"# .decode("utf-8")이 없으면 jsn에는 str이 아닌 bytes가 저장 된다.
        # If the end of the file has been reached, read() will return an empty string ('').
        print(jsn)        
        # print(json.dumps(jsn, indent="\t")) 는 indent가 적용되어 출력되어야 하지만 원본이 indent가 적용되어 있지
        # 않아 indent 없이 출력 된다.
        with open(filename, mode="wt", encoding="utf-8") as f:
            f.write(jsn)
 
with open(filename, mode="rt", encoding="utf-8") as f:
    items = json.load(f) # JSON 문서를 갖고 있는 파일 포인터 전달. loads()는 JSON 형식의 문자열 전달
    for item in items:
        print("Name:", item["name"], "Login:", item["owner"]["login"])
 
test = {
    "Date" : "2019-01-17",
    "Time" : "21:30:24",
    "Location" : {
        "Town" : "Franklin",
        "City" : "Newyork",
        "Country" : "USA"
        }
    }
 
= json.dumps(test, indent="\t")
# Serialize obj to a JSON formatted str
# If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed
# with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects
# the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a
# string (such as "\t"), that string is used to indent each level.
print(s)
 
with open("dump.json", mode="wt") as f:
    json.dump(test, f, indent="\t")
# Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
cs


출력 결과 처음 부분.


출력 결과 마지막 부분.


write()으로 만든 repositories.json과 dump()으로 만든 dump.json 파일.



반응형
Posted by J-sean
:
반응형

Beautifulsoup을 이용해 XML을 분석할 수 있다.


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
from bs4 import BeautifulSoup
import urllib.request as req
import os.path
 
url = "http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108"
# 기상청 날씨누리 전국 중기예보 RSS
filename = "forecast.xml"
 
if not os.path.exists(filename):
    #req.urlretrieve(url, savename)
    # Legacy interface. It might become deprecated at some point in the future.
    with req.urlopen(url) as contents:
        xml = contents.read().decode("utf-8")
        # If the end of the file has been reached, read() will return an empty string ('').
        #print(xml)
        with open(filename, mode="wt") as f:
            f.write(xml)
 
with open(filename, mode="rt") as f:
    xml = f.read()
    soup = BeautifulSoup(xml, "html.parser")
    # html.parser는 모든 태그를 소문자로 바꾼다.
    #print(soup)
 
    print("[", soup.find("title").string, "]")
    print(soup.find("wf").string, "\n")
 
    # 날씨에 따른 지역 분류
    info = {}    # empty dicionary
    for location in soup.find_all("location"):
        name = location.find("city").string
        weather = location.find("wf").string
        if not (weather in info):
            info[weather] = []    # empty list. dictionary는 list를 value로 가질 수 있다.
        info[weather].append(name)
 
    for weather in info.keys():    # Return a new view of the dictionary’s keys.
        print("■", weather)
        for name in info[weather]:
            print("|-", name)
cs




반응형
Posted by J-sean
:
반응형

Selenium과 Chrome driver를 이용해 웹싸이트에서 로그인이 필요한 정보를 가져 올 수 있다.

아래 코드는 인터넷 서점(Yes24)에 접속해서 로그인 하고 주문 내역을 가져 온다.

Chrome이 동작하는걸 보고 싶다면 options 관련 부분만 삭제하면 된다.

 

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
from selenium import webdriver
 
login_url = "https://www.yes24.com/Templates/FTLogin.aspx"
id = "아이디"
password = "패스워드"
 
options = webdriver.ChromeOptions()
options.add_argument("headless"# headless 모드
options.add_argument("window-size=1920x1080"# headless 모드가 아니면 의미가 없는거 같다.
options.add_argument("--log-level=3"# 이 코드가 없으면 headless 모드시 log가 많이 표시 된다.
 
#driver = webdriver.Chrome("c:\download\chromedriver.exe", options = options)
driver = webdriver.Chrome(options = options) # webdriver와 소스가 같은 폴더에 있을 때.
driver.implicitly_wait(3)
driver.get(login_url)
print("Title: %s\nLogin URL: %s" %(driver.title, driver.current_url))
 
id_elem = driver.find_element_by_id("SMemberID")
id_elem.clear()
id_elem.send_keys(id)
 
driver.find_element_by_id("SMemberPassword").clear()
driver.find_element_by_id("SMemberPassword").send_keys(password)
# clear()와 send_keys()는 None을 리턴 한다.
 
login_btn = driver.find_element_by_xpath('//*[@id="btnLogin"]')
login_btn.click() # None 리턴
# driver.find_element_by_xpath('//*[@id="btnLogin"]').click()
 
list_url = "https://ssl.yes24.com//MyPageOrderList/MyPageOrderList"
driver.get(list_url)
 
print("-" * 30"Order list""-" * 30)
lists = driver.find_elements_by_css_selector("#MyOrderListTbl span")
for i, item in enumerate(lists):
    print("%d: %s" %(i + 1, item.text))
 
driver.save_screenshot("screenshot.png")
 
#driver.quit()
cs

 

 

38번 라인에서 캡쳐한 'screenshot.png'

 

 

※ Selenium Documentation

 

반응형
Posted by J-sean
:
반응형

urllib와 beautifulsoup을 이용해 Naver에서 '이 시각 주요 뉴스' 목록을 가져온다.


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
from bs4 import BeautifulSoup as bs
import urllib.request as req
 
url = 'https://news.naver.com/'
res = req.urlopen(url)
 
soup = bs(res, 'html.parser')
title1 = soup.find('h4''tit_h4').string # 'tit_h4 tit_main1'
# title1 = soup.find(attrs = {'class' : 'tit_h4 tit_main1'}).string
print('\t\tNAVER', title1, '\n'
 
print('-'*20'find_all()''-'*20)
headlines1 = soup.find_all('a''nclicks(hom.headcont)')
# headlines1 = soup.find_all(attrs = {'class' : 'nclicks(hom.headcont)'})
# The find_all() method looks through a tag’s descendants and
# retrieves all descendants that match your filters.
for i, news in enumerate(headlines1):
    #if news.string == None:
    #    print('%2d: None' %i)
    #    continue
    print('%2d: %s' %(i + 1, news.string))
 
print('-'*20'select()''-'*20)
headlines2 = soup.select('div.newsnow_tx_inner > a')
# Beautiful Soup supports the most commonly-used CSS selectors. Just pass a
# string into the .select() method of a Tag object or the BeautifulSoup object itself.
for i, news in enumerate(headlines2):
    #if news.string == None:
    #    print('%2d: None' %i)
    #    continue
    print('%2d: %s' %(i + 1, news.string))
cs



반응형
Posted by J-sean
: