#
# import requests
# from bs4 import BeautifulSoup
#
# f = open("Daum_News.csv", "w", encoding="UTF=8")
# f.write("title,summary\n")
#
# for i in range(1,4):
#     raw = requests.get("https://search.daum.net/search?w=news&q=이스라엘&DA=PGD&spacing=0&p="+str(i))
#     html = BeautifulSoup(raw.text, 'html.parser')
#     news = html.select("ul.list_info>li")
#
#     for ns in news:
#         title = ns.select_one("div.mg_tit").text.strip().replace(",",".")
#         summary = ns.select_one("p.desc").text.strip().replace(",",".")
#         f.write(title + "," + summary + "\n")
#
# f.close()

import requests
from bs4 import BeautifulSoup
import openpyxl

key = input("검색어를 입력하십시오. : ")

try:
    wb = openpyxl.load_workbook("daumNews.xlsx")
    sheet1 = wb.create_sheet(key)
    sheet1.append(["title", "summary"])
    print("기존에 있는 파일에 새 시트로 입력하였습니다.")

except:
    wb = openpyxl.Workbook()
    sheet1 = wb.active
    sheet1.append(["title", "summary"])
    sheet1.title = key
    print("새 파일을 작성하였습니다.")

for i in range(1,4):
    raw = requests.get("https://search.daum.net/search?w=news&q="+key+"&DA=PGD&spacing=0&p="+str(i))
    html = BeautifulSoup(raw.text, "html.parser")
    news = html.select("div.cont_inner")

    for ns in news:
        title = ns.select_one("div.wrap_tit").text.strip()
        summary = ns.select_one("p.desc").text.strip()
        sheet1.append([title, summary])

wb.save("daumNews.xlsx")

하나씩 해보는 재미가 쏠쏠합니다. 

초보적인 수준에 불과하겠지만,

복사하고 붙여 넣기보다는 직접 한 글자, 한 글자 입력해 보면서 하는 것이 더 좋은 것 같군요.

 

패키지 혹은 라이브러리의 쓰임새가 무궁무진하겠군요.

이제 겨우 requests, BeautifulSoup, openpyxl 세 가지 써봤습니다.

 

뭐, 걸음마 하는 수준이니까요. 계속 걸어가 보렵니다. 

 

PS. py파일명을 패키지와 같은 이름으로 했다가 한 시간을 허비했습니다. 계속 오류가 나더군요.

이런 것은 몸으로 배워야 하나 봅니다. 

파일명, 변수명은 중복되지 않도록 두 단어 이상 붙일 것.

 

'코딩' 카테고리의 다른 글

Toy Project - 캘린더, 지도, 모임  (0) 2021.06.23
나총무 - 내가총무다  (0) 2021.06.23
python - 데이터 수집기 예제  (0) 2021.05.15
python - Scraping 도전중  (0) 2021.05.12
python 기초 - 쉬운게 없다.  (0) 2021.05.10

+ Recent posts