생각하는 감쟈
[Python] 3-1) 데이터 수집 및 크롤링 본문
13일차 (23.03.29)

✔데이터 분석이 필요한 이유
1 데이터는 모든 현상과 가설의 근거가 되는 정보를 담고 있음
2 직접 경험하지 않아도 데이터를 통해 경험을 얻을 수 있음
3 데이터 분석을 통해 데이터에서 의미를 찾고 비래를 예측하는 등 새로운 가치를 창출 가능
비즈니스에 대한 정보가 매 순간 데이터로 기록 > 데이터의 종류, 양, 접근성
> 데이터를 이해하고 활용할 수 있는 능력 > 데이터 분석을 통한 가치 창출

`✔웹 스크래핑/크롤링
requests
BeautifulSoup
import requests
from bs4 import BeautifulSoup
# import requests
# from bs4 import BeautifulSoup
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start=11"
# https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start=21
# https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=28&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start=31
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
# 변수로 페이지를 지정해서 10번째 페이지를 읽어오세요.
page = 10
start = (page-1) * 10 + 1
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
# page를 넣으면 그 페이지의 뉴스를 가져오는 함수를 만들고, 그 함수를 호출하세요.
#page = 10
def getNews(page):
start = (page-1) * 10 + 1
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
getNews(5)
def getNews(keyword, page):
start = (page-1) * 10 + 1
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query={keyword}&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
getNews('파이썬', 5)
위코드에서 키워드를 입력하여 출력할 수 있게 코드 변경
# 키워드와 페이지를 입력 받음. 페이지 번호가 4라면 1~4페이지를 읽어온다.(처음부터 입력한 페이지까지 읽기)
def getNews(k, p):
#for i in range(1, p+1): # 5==>1,2,3,4,5 5==>0,1,2,3,4
for i in range(p): # 5==>0,1,2,3,4
start = i * 10 + 1 # 1,11,21,31,41
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query={k}&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
keyword = input('어떤 내용을 검색하시겠습니까? ')
page = int(input('몇 번째 페이지까지 읽어오겠습니까? '))
getNews(keyword, page)
# 키워드와 페이지를 입력 받음. 페이지 번호가 4라면 1~4페이지를 읽어온다.(처음부터 입력한 페이지까지 읽기)
def getNews(k, p):
#for i in range(1, p+1): # 5==>1,2,3,4,5 5==>0,1,2,3,4
for i in range(p): # 5==>0,1,2,3,4
start = i * 10 + 1 # 1,11,21,31,41
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query={k}&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
keyword = input('어떤 내용을 검색하시겠습니까? ')
print(keyword.split())
for k in keyword.split():
print(k)page = int(input('몇 번째 페이지까지 읽어오겠습니까? '))
getNews(keyword, page)
def getNews(keyword, p):
for k in keyword.split():
print("===k)
for i in range(p): # 5==>0,1,2,3,4
start = i * 10 + 1 # 1,11,21,31,41
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query={k}&sort=0&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
keyword = input('어떤 내용을 검색하시겠습니까? ')
page = int(input('몇 번째 페이지까지 읽어오겠습니까? '))
getNews(keyword, page)
# 최신순으로 뉴스를 검색하고 싶다
def getNews(keyword, p, sort):
for k in keyword.split():
print("\n\n===",k,'===')
for i in range(p): # 5==>0,1,2,3,4
start = i * 10 + 1 # 1,11,21,31,41
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query={k}&sort={sort}&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
print(title.text)
keyword = input('어떤 내용을 검색하시겠습니까? ')
page = int(input('몇 번째 페이지까지 읽어오겠습니까? '))
getNews(keyword, page, 1)
import pandas as pd
# 뉴스 제목만 csv 파일로 저장
# 컬럼: '뉴스제목'
# 내용: "중국, 인공지능 활용 박차…'과학을 위한 AI' 프로젝트 시작"
# [[1,2,3],[4,5,6]]
# 컬럼이름 A,B,C
pd.DataFrame([[1,2,3],[4,5,6]], columns=['A','B','C'])
pd.DataFrame(["중국, 인공지능 활용 박차…'과학을 위한 AI' 프로젝트 시작"], columns=['뉴스제목'])
pd.DataFrame({'뉴스제목':["중국, 인공지능 활용 박차…'과학을 위한 AI' 프로젝트 시작", 'a','b']})
# pd,read_csv("a.csv")
# pd.to_csv("a.csv")
page = 2
q = '파이썬'
url = "http://www.naver.com?page=1&q=인공지능"
url = "http://www.naver.com?" + "page=" + str(page) + "&q=" + q
start = (page-1) * 10 + 1
#start = 1
url = f"http://www.naver.com?start={start}"
print(url)
import pandas as pd
def getNews(keyword, p, sort, fname):
newslist = []
for k in keyword.split():
print("\n\n===",k,'===')
for i in range(p): # 5==>0,1,2,3,4
start = i * 10 + 1 # 1,11,21,31,41
url = f"https://search.naver.com/search.naver?where=news&sm=tab_pge&query={k}&sort={sort}&photo=0&field=0&pd=0&ds=&de=&cluster_rank=13&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:all,a:all&start={start}"
response = requests.get(url)
html = response.text
bs_obj = BeautifulSoup(html, "html.parser")
titles = bs_obj.select('.news_tit')
for title in titles:
newslist.append(title.text)
#print(title.text)
print(newslist)
df = pd.DataFrame({'뉴스제목': newslist})
df.to_csv(fname)
keyword = input('어떤 내용을 검색하시겠습니까? ')
page = int(input('몇 번째 페이지까지 읽어오겠습니까? '))
getNews(keyword, page, 1, "네이버뉴스.csv")
df = pd.read_csv("네이버뉴스.csv")
df
이게 맞아
?

#ABC부트캠프 #부트캠프 #유클리드소프트 #파이썬 #고용노동부 #한국산업인력공단 #청년친화형 #ESG지원사업 #대전 #서포터즈 #python #Ai #Bigdata #cloud #대외활동 #대학생 #daily
'Language > Python' 카테고리의 다른 글
[Python] 4-1) 머신러닝 기초 (0) | 2023.04.06 |
---|---|
[Python] 3-2) 정규표현식, 워드클라우드 (0) | 2023.04.06 |
[Python] 2-5) Matplotlib 2 (0) | 2023.03.29 |
[Python] 2-5) Matplotlib 1 (0) | 2023.03.29 |
[Python] 2-4) Data Frame 2 (1) | 2023.03.28 |
Comments