반응형

네이버에서 환율 정보를 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
:
반응형

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
:
반응형

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
: