목표: 저장해 두었던 텍스트 파일을 불러온 뒤, 페이지에 접속하여 미디어, 작성 날짜, 본문 등의 내용을 추가적으로 수집하여 파일로 저장함
import requests
from lxml import html
import time
keyword='떡볶이'
input_file_name='naver_news_떡볶이_211127_110440.txt'
output_file_main_name='naver_news_main_' +keyword + "_" +time.strftime("%y%m%d_%H%M%S") + '.txt'
output_file_main=open(output_file_main_name,"w",encoding="utf-8")
output_file_main.write("{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n".format('번호','키워드','매체','날짜','제목','URL','본문'))
output_file_main.close()
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.118 Whale/2.11.126.23 Safari/537.36'}
def fget_list():
input_file=open(input_file_name,"r", encoding="utf-8")
input_text=input_file.read()
lines=input_text.splitlines()
lists=[]
for line in lines[:]:
elms=line.strip().split("\\t")
news_title=elms[2]
try:
url=elms[3]
except:
url=''
lists.append([news_title,url])
return lists[1:]
def fwrite_news_main(count, news_media,news_date, news_title, news_url, news_article):
print([count,keyword,count, news_media,news_date, news_title, news_url, news_article])
output_file_main=open(output_file_main_name,"a",encoding="utf-8")
output_file_main.write("{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n".format(count,keyword,count,
news_media,news_date,
news_title, news_url,
news_article))
return
def fcrawl_news_main(count, news_title, news_url):
html_req=requests.get(news_url,headers=headers)
tree=html.fromstring(html_req.content)
try:
news_media=tree.xpath('//div[@class="press_logo"]/a/img/@title')[0]
except:
news_media=''
try:
news_date=tree.xpath('//div[@class="sponsor"]/span/text()')[0]
except:
news_date=''
try:
news_article=tree.xpath('//div[@class="articleBodyContents"]/descendant-or-self::text()[not(ancestor::script)]')
except:
news_article=''
news_article=" ".join(news_article).replace("\\n"," ").replace("\\t"," ").replace("\\r"," ").strip()
fwrite_news_main(count, news_media, news_date, news_title, news_url, news_article)
return
def fmain():
lists=fget_list()
count=1
for list in lists[:]:
print(list)
news_title=list[0]
news_url=list[1]
if len(news_url)==0:
continue
fcrawl_news_main(count,news_title,news_url)
time.sleep(6)
count +=1
⭐기존에 저장되어 있던 파일 불러오기,
저장할 새로운 파일 생성해두기
keyword='떡볶이'
input_file_name='naver_news_떡볶이_211127_110440.txt'
#수집한 목록 파일을 가지고 오기 위해 input_file_name 변수에 값을 입력해줌
output_file_main_name='naver_news_main_' +keyword + "_" +time.strftime("%y%m%d_%H%M%S") + '.txt'
output_file_main=open(output_file_main_name,"w",encoding="utf-8")
output_file_main.write("{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n".format('번호','키워드','매체','날짜','제목','URL','본문'))
#번호, 키워드, 매체, 날짜, 제목, url, 본문을 저장한 파일 열머리글을 입력
output_file_main.close()
⭐수집한 목록 파일을 불러와서 lists 목록에 넣는 함수 생성
def fget_list():
#수집한 목록 파일을 불러오는 함수 생성
input_file=open(input_file_name,"r", encoding="utf-8")
#파일 불러온 뒤, "r" mode를 사용합니다 "r"은 읽기를 뜻함
input_text=input_file.read()#불러온 파일을 읽어서 input_text에 저장
lines=input_text.splitlines()#저장된 내용을 line단위로 잘라서 목록 형태로 만듦
lists=[]
for line in lines[:]:#불러온 파일을 한 라인씩(한 행 씩)불러옴
elms=line.strip().split("\\t")#불러온 라인의 내용을 탭(\\t)일 기준으로 나눔눔
news_title=elms[2]#나눈 항목의 3번째 항목을 news_title에 입력
try:
url=elms[3]#나눈 항목의 4번째 항목을 url에 입력
except:
url=''#url이 없는 경우도 있기 때문에, ,url이 없으면 오류가 발생
#따라서 try except문 활용하여 예외 처리
lists.append([news_title,url])#앞서 만들어둔 lists변수에 저장
return lists[1:] #lists의 1번 행은 열머리 글이기 때문에 1행을 제외하고 보냄
⭐
def fwrite_news_main(count, news_media,news_date, news_title, news_url, news_article):
print([count,keyword,count, news_media,news_date, news_title, news_url, news_article])
output_file_main=open(output_file_main_name,"a",encoding="utf-8")
output_file_main.write("{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n".format(count,keyword,count,
news_media,news_date,
news_title, news_url,
news_article))
return
⭐ html 정보 수집 함수 만들기
def fcrawl_news_main(count, news_title, news_url):
html_req=requests.get(news_url,headers=headers)
tree=html.fromstring(html_req.content)
try:
news_media=tree.xpath('//div[@class="press_logo"]/a/img/@title')[0]
except:
news_media=''
try:
news_date=tree.xpath('//div[@class="sponsor"]/span/text()')[0]
except:
news_date=''
try:
news_article=tree.xpath('//div[@class="articleBodyContents"]/descendant-or-self::text()[not(ancestor::script)]')
except:
news_article=''
news_article=" ".join(news_article).replace("\\n"," ").replace("\\t"," ").replace("\\r"," ").strip()
fwrite_news_main(count, news_media, news_date, news_title, news_url, news_article)
return
news_media=tree.xpath('//div[@class="press_logo"]/a/img/@title')[0]