til 2022-12-06

JYR00·2022년 12월 6일
1

TIL

목록 보기
43/60

기사 본문 txt에 저장하기

# ex7.py
# 기사 본문 내용 article_total.txt에 저장되어있다
import os,re
import urllib.request as ur
from bs4 import BeautifulSoup as bs

url = "https://news.daum.net/"
html = ur.urlopen(url)
soup = bs(html.read(),'html.parser')

f = open('./data/article_total.txt','w',encoding='utf-8')

for i in soup.find_all('div',{'class':'item_issue'}):
    try:
        # print(i.text)
        # print(i.find_all('a')[0].get('href'))
        f.write(i.text+'\n')
        f.write(i.find_all('a')[0].get('href') + "\n")
        html2 = ur.urlopen(i.find_all('a')[0].get('href'))


        soup2 = bs(html2.read(),'html.parser')
        for j in soup2.find_all('p'):
            # print(j.text+'\n')
            f.write(j.text + '\n')
    except:
        pass
f.close()



pandas

cmd로 설치(original 방법)

tool로 설치


numpy도 마찬가지로 설치해준다

# ex1.py

import numpy as np

# print(np.__version__)

ar1 = np.array([1,2,3,4,5])
# print(ar1)
# print(type(ar1))

ar2 = np.array([[1,2,3,4,5],[6,7,8,9,10]]) #크기가 같아야 하나봄
# print(ar2)

ar3 = np.arange(1,11,2) #1에서 11까지 증가값이 2(홀수)
# print(ar3)

ar4 = np.arange(1,31,3) # 31포함 안됨
# print(ar4)

ar5 = np.array([1,2,3,4,5,6]).reshape((3,2)) #2개씩 3줄로 출력(3행 2열)
# print(ar5)

ar6 = np.zeros((2,3))
# print(ar6)
# [[0. 0. 0.]
#  [0. 0. 0.]]  0으로 2열 3행

ar7 = np.array([[10,20,30],[40,50,60]])
ar8 = ar7[0:2,0:2]
# print(ar8)
# [[10 20] [index번호 : 갯수] 디폴트가 0. [:5] 5개를 가져온다
#  [40 50]]

ar9 = ar7[0:]
ar10 = ar7[0,:]
# print(ar9)
# print("--------------------")
# print(ar10)

# ar9 = ar7[0:]
# [[10 20 30]
#  [40 50 60]]

# ar10 = ar7[0,:]
# [10 20 30]
# 두 개의 차이가 존재한다

ar11 = np.array(([1,2,3,4,5]))
ar12 = ar11 + 10
print(ar12)
# [11 12 13 14 15]  요소들 마다 값이 더해진다

ar13 = ar11 +ar12
print(ar13)
# [12 14 16 18 20]
# 세로로 값이 더해짐

ar14 = ar13 * 2
print(ar14)
# [24 28 32 36 40] // [12 14 16 18 20]에서 각 항목이 *2됨











그래프 만들기


#ex5.py

import matplotlib.pyplot as plt

x = [2016,2017,2018,2019,2020]
y = [350,410,520,695,543]



plt.plot(x,y)
plt.title('Annual Sales')
plt.xlabel('year')
plt.ylabel('sales')
plt.show()

# plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
# plt.show()

막대그래프 그리기

# ex5.py
# 막대그래프

import matplotlib.pyplot as plt

y1 = [350,410,520,695]
y2 = [200,250,385,350]
x = range(len(y1))
print(x)
# range(0, 4)
# y1,y2값이 합쳐진 막대 그래프 약간 소다맛 아이스크림 같은

plt.bar(x,y1, width=0.7, color = 'blue')
plt.bar(x,y2, width=0.7, color = 'red', bottom=y1)
# y1이 아래에 있고 y2가 위에 있음

plt.title('Quarterly Sales')
plt.xlabel('Quarters')
plt.ylabel('Sales')
xLabel = ['first','second','third','fourth']
plt.xticks(x,xLabel, fontsize = 10)

plt.legend(['chairs','desks'])

plt.show()

네이버 개발자 센터

https://developers.naver.com/main/
회원가입을 한다

언어별로 받아오는 곳
https://developers.naver.com/docs/serviceapi/datalab/search/search.md#python

네이버 기사 크롤링하기


#nvCrawler.py

import os,sys
import urllib.request
import datetime, time
import json

client_id ="TY0XEecDCcFWi33nL8uC"
client_secret="5U0WY4HGc7"

# [CODE 1]
def getRequestUrl(url):
    req = urllib.request.Request(url)
    req.add_header("X-Naver-Client-Id", client_id)
    req.add_header("X-Naver-Client-Secret", client_secret)

    try:
        response = urllib.request.urlopen(req)
        if response.getcode() == 200:
            print("[%s] Url Request Success" % datetime.datetime.now())
            return response.read().decode('utf-8')
    except Exception as e:
        print(e)
        print("[%s] Error for URL : %s" % (datetime.datetime.now(), url))
        return None


# [CODE 2] : 네이버 뉴스를 반환하고 json 형식으로 반환
def getNaverSearch(node, srcText, start, display):
    base = "https://openapi.naver.com/v1/search"
    node = "/%s.json" % node
    parameters = "?query=%s&start=%s&display=%s" % (urllib.parse.quote(srcText), start, display)

    url = base + node + parameters
    responseDecode = getRequestUrl(url)  # [CODE 1]

    if (responseDecode == None):
        return None
    else:
        return json.loads(responseDecode)


# [CODE 3] : json data를 list 타입으로 변환
def getPostData(post, jsonResult, cnt):
    title = post['title']
    description = post['description']
    org_link = post['originallink']
    link = post['link']

    pDate = datetime.datetime.strptime(post['pubDate'], '%a, %d %b %Y %H:%M:%S +0900')
    pDate = pDate.strftime('%Y-%m-%d %H:%M:%S')

    jsonResult.append({'cnt': cnt, 'title': title, 'description': description,
                       'org_link': org_link, 'link': org_link, 'pDate': pDate})
    return

# [CODE 0]
def main():
    node = 'news'  # 크롤링 할 대상
    srcText = input('검색어를 입력하세요: ')
    cnt = 0
    jsonResult = []

    jsonResponse = getNaverSearch(node, srcText, 1, 100)  # [CODE 2]
    total = jsonResponse['total']

    while ((jsonResponse != None) and (jsonResponse['display'] != 0)):
        for post in jsonResponse['items']:
            cnt += 1
            getPostData(post, jsonResult, cnt)  # [CODE 3]

        start = jsonResponse['start'] + jsonResponse['display']
        jsonResponse = getNaverSearch(node, srcText, start, 100)  # [CODE 2]

    print('전체 검색 : %d 건' % total)

#     json타입으로 진행
    with open('./data/%s_naver_%s.json' % (srcText,node),'w',encoding='utf-8') as outfile :
        jsonFile = json.dumps(jsonResult, indent=4, sort_keys=True, ensure_ascii=False)
        outfile.write(jsonFile)
    print("가져온 데이터 : %d건" % (cnt))
    print('%s_naver_%s.json SAVED' % (srcText,node))
if __name__ == '__main__' :
    main()

출입국관광서비스 통계
https://www.data.go.kr/data/15000297/openapi.do





서비스 url도 여기있음

# ch05/openapi_tour.py

import os, sys
import urllib.request
import datetime, time
import json
import pandas as pd

serviceKey = 's9CuSdYlF8MMsvHSesTMknvCXypbgH4qkKBQnYJef6KoOyY6SNBfCLafHV6WyOM2Ac1pARCLRHv3HFaMrehU4g%3D%3D'


# [CODE 1]
def getRequestUrl(url):
  req = urllib.request.Request(url)
  try:
    response = urllib.request.urlopen(req)
    if response.getcode() == 200:
      print("[%s] Url Request Success" % datetime.datetime.now())
      return response.read().decode('utf-8')
  except Exception as e:
    print(e)
    print("[%s] Error for URL : %s" % (datetime.datetime.now(), url))
    return None


# [CODE 2] : url 구성하여 데이터 요청
def getTourismStatsItem(yyyymm, national_code, ed_cd):  # ed_cd : 방한외래관광객 or 해외 출국
  service_url = 'http://openapi.tour.go.kr/openapi/service/EdrcntTourismStatsService/getEdrcntTourismStatsList'
  parameters = "?_type=json&serviceKey=" + serviceKey  # 인증키
  parameters += "&YM=" + yyyymm
  parameters += "&NAT_CD=" + national_code
  parameters += "&ED_CD=" + ed_cd
  url = service_url + parameters

  retData = getRequestUrl(url)  # [CODE 1]

  if (retData == None):
    return None
  else:
    return json.loads(retData)


# [CODE 3]
def getTourismStatsService(nat_cd, ed_cd, nStartYear, nEndYear):
  jsonResult = []
  result = []
  natName = ''
  dataEND = "{0}{1:0>2}".format(str(nEndYear), str(12))  # 데이터 끝 초기화
  isDataEnd = 0  # 데이터 끝 확인용 flag 초기화

  for year in range(nStartYear, nEndYear + 1):
    for month in range(1, 13):
      if (isDataEnd == 1): break  # 데이터 끝 flag 설정되어있으면 작업 중지.
      yyyymm = "{0}{1:0>2}".format(str(year), str(month))
      jsonData = getTourismStatsItem(yyyymm, nat_cd, ed_cd)  # [CODE 2]

      if (jsonData['response']['header']['resultMsg'] == 'OK'):
        # 입력된 범위까지 수집하지 않았지만, 더이상 제공되는 데이터가 없는 마지막 항목인 경우 -------------------
        if jsonData['response']['body']['items'] == '':
          isDataEnd = 1  # 데이터 끝 flag 설정
          dataEND = "{0}{1:0>2}".format(str(year), str(month - 1))
          print("데이터 없음.... \n 제공되는 통계 데이터는 %s년 %s월까지입니다."
                % (str(year), str(month - 1)))
          break
          # jsonData를 출력하여 확인......................................................
        print(json.dumps(jsonData, indent=4,
                         sort_keys=True, ensure_ascii=False))
        natName = jsonData['response']['body']['items']['item']['natKorNm']
        natName = natName.replace(' ', '')
        num = jsonData['response']['body']['items']['item']['num']
        ed = jsonData['response']['body']['items']['item']['ed']
        print('[ %s_%s : %s ]' % (natName, yyyymm, num))
        print('----------------------------------------------------------------------')
        jsonResult.append({'nat_name': natName, 'nat_cd': nat_cd,
                           'yyyymm': yyyymm, 'visit_cnt': num})
        result.append([natName, nat_cd, yyyymm, num])

  return (jsonResult, result, natName, ed, dataEND)


# [CODE 0]
def main():
  jsonResult = []
  result = []
  natName = ''
  print('<< 국내 입국한 외국인의 통계 데이터를 수집합니다.>>')
  nat_cd = input('국가 코드를 입력하세요(중국: 112 / 일본: 130 / 미국: 275) :')
  nStartYear = int(input('데이터를 몇 년부터 수집할까요?'))
  nEndYear = int(input('데이터를 몇 년까지 수집할까요?'))
  ed_cd = input('E : 발한외래관광객, D : 해외출국 입력하시오 알파벳 하나만 치시오')
  # ed_cd = 'E'   # E : 발한외래관광객, D : 해외출국
  # ed_cd = "D"

  jsonResult, result, natName, ed, dataEND = getTourismStatsService(nat_cd, ed_cd, nStartYear, nEndYear)

  if (natName == ''):
    print('데이터가 전달되지 않았습니다. 공공데이터포털의 서비스 상태를 확인하시기 바랍니다.')
  else :
    # 파일 저장 : json 파일
    with open('./data/%s_%s5, %d_%s,%s.json' % (natName, ed, nStartYear, dataEND, ed_cd), 'w', encoding='utf-8') as outfile:
      jsonFile = json.dumps(jsonResult, indent=4, sort_keys=True, ensure_ascii=False)
      outfile.write(jsonFile)
    # 파일 저장 : ccsv 필요
    columns =['입국자 국가', '국가코드', '입국년월', '입국자 수']
    result_df = pd.DataFrame(result,columns=columns)
    result_df.to_csv('./data/%s_%s5, %d_%s.csv' % (natName, ed, nStartYear, dataEND),
                       index=False, encoding='cp949')


if __name__ == '__main__':
  main()

서울광장 서울 민주주의 자유제안
https://data.seoul.go.kr/dataList/OA-2563/S/1/datasetView.do

#openApi_Seoul.py : 민주주의 서울 자유제안 정보

import os, sys
import urllib.request
import datetime, time
import json
import pandas as pd

#서울열린광장에서 받은 개인 인증키
serviceKey="5155506b6173696d37357446486963"

#[CODE 1]
def getRequestUrl(url):
    req = urllib.request.Request(url)
    try:
        response = urllib.request.urlopen(req)
        if response.getcode() == 200:
            print ("[%s] Url Request Success" % datetime.datetime.now())
            return response.read().decode('utf-8')
    except Exception as e:
        print(e)
        print("[%s] Error for URL : %s" % (datetime.datetime.now(), url))
        return None

# [CODE 2] '서울 열린테이터 광장 : 한 page에 5개만 display됨.
def getPage(start):
    url = 'http://openapi.seoul.go.kr:8088/' + serviceKey + '/json/ChunmanFreeSuggestions/%d/%d' % (start, start + 4)
    retData = getRequestUrl(url)  # [CODE 1]

    if (retData == None):
        return None
    else:
        return json.loads(retData)


#[CODE 3]  "서울 열린데이터 광장" : 최대 1000개까지만 제공
def getItemsAll():
    result = []
    for i in range(1000//5):
        jsonData = getPage(i*5 +1) #[CODE 2]
        if (jsonData['ChunmanFreeSuggestions']['RESULT']['CODE'] == 'INFO-100'):
            print("인증키가 유효하지 않습니다!!")
            return

        if(jsonData['ChunmanFreeSuggestions']['RESULT']['CODE'] == 'INFO-000'):
            for i in range(5):
                SN = jsonData['ChunmanFreeSuggestions']['row'][i]['SN']
                TITLE = jsonData['ChunmanFreeSuggestions']['row'][i]['TITLE']
                CONTENT_link = jsonData['ChunmanFreeSuggestions']['row'][i]['CONTENT']
                DATE = jsonData['ChunmanFreeSuggestions']['row'][i]['REG_DATE']
                result.append([SN, TITLE, CONTENT_link, DATE])
    return result

#[CODE 0]
def main():
    jsonResult = []
    result =[]

    print("<<현재 기준 '민주주의서울 자유제안' 데이터 1000개를 수집합니다.>>")
    result = getItemsAll()

    #파일저장
    columns = ['SN',"TITLE","CONTENT_LINK", "DATE"]

    result_df = pd.DataFrame(result, columns=columns)
    result_df.to_csv('./data/민주주의서울자유제안.csv', index=False, encoding='cp949')
if __name__ == '__main__':
    main()

파일로 저장이 된다




















1개의 댓글

comment-user-thumbnail
2022년 12월 7일

좋은글 잘 보고 갑니다~

답글 달기