본문 바로가기
빅데이터 부트캠프/Crawling&Scraping

빅데이터 부트캠프 34일차

by Mecodata 2022. 8. 22.
import sys # 변수와 함수를 직접 제어
from bs4 import BeautifulSoup # HTML과 XML 파싱에 사용
import urllib.request # 간편한 HTTP 요청 처리를 위해 사용
from urllib.parse import quote

TARGET_URL_BEFORE_PAGE_NUM = 'http://news.donga.com/search?p='
TARGET_URL_BEFORE_KEWORD = '&query='
TARGET_URL_REST = '&check_news=1&more=1&sorting=3&search_date=1&v1=&v2=&range=3'

# 기사 검색 페이지에서 기사 제목에 링크된 기사 본문 주소 받아오기
def get_link_from_news_title(page_num, URL, output_file):
    for i in range(page_num):
        current_page_num = 1 + i*15
        position = URL.index('=')
        URL_with_page_num = URL[: position+1] + str(current_page_num) + URL[position+1 :]
        source_code_from_URL = urllib.request.urlopen(URL_with_page_num)
        soup = BeautifulSoup(source_code_from_URL, 'lxml', from_encoding='utf-8')
        for title in soup.find_all('p', 'tit'):
            title_link = title.select('a')
            article_URL = title_link[0]['href']
            get_text(article_URL, output_file)

# 기사 본문 내용 긁어오기
def get_text(URL, output_file):
    source_code_from_url = urllib.request.urlopen(URL)
    soup = BeautifulSoup(source_code_from_url, 'lxml', from_encoding='utf-8')
    content_of_article = soup.select('div.article_txt')
    for item in content_of_article:
        string_item = str(item.find_all(text=True))
        output_file.write(string_item)

# 메인함수
def main(argv):
    if len(argv) != 4: # python은 인자값이 아닌 것을 sys.argv가 알아서 구분함
        print('python [모듈이름] [키워드] [가져올 페이지 숫자] [결과 파일명]')
        return
    keyword = argv[1]
    page_num = int(argv[2])
    output_file_name = argv[3]
    target_URL = TARGET_URL_BEFORE_PAGE_NUM + TARGET_URL_BEFORE_KEWORD + quote(keyword) + TARGET_URL_REST
    output_file = open(output_file_name, 'w', encoding='utf-8')
    get_link_from_news_title(page_num, target_URL, output_file)
    output_file.close()

if __name__ == '__main__': # 함수 중에서 main함수를 가장 먼저 실행하겠다는 걸 정의
    main(sys.argv) # sys.argv = terminal을 통해 인자값을 받을 수 있도록 명령
import sys
from konlpy.tag import Twitter
from collections import Counter

def get_tags(text, ntags=100):
    spliter = Twitter()
    nouns = spliter.nouns(text)
    count = Counter(nouns)
    return_list = []
    for n, c in count.most_common(ntags):
        temp = {'tag': n, 'count': c}
        return_list.append(temp)
    return return_list

# 메인함수
def main(argv):
    if len(argv) != 4: # python은 인자값이 아닌 것을 sys.argv가 알아서 구분함
        print('python [모듈이름] [텍스트 파일명.txt] [단어 개수] [결과 파일명.txt]')
        return
    text_file_name = argv[1]
    noun_count = int(argv[2])
    output_file_name = argv[3]
    open_text_file = open(text_file_name, 'r', encoding='utf-8')
    text = open_text_file.read()
    tags = get_tags(text, noun_count)
    open_text_file.close()
    open_output_file = open(output_file_name, 'w', encoding='utf-8')
    for tag in tags:
        noun = tag['tag']
        count = tag['count']
        open_output_file.write('{}  {}\n'.format(noun, count))
    open_output_file.close()

if __name__ == '__main__':  # 함수 중에서 main함수를 가장 먼저 실행하겠다는 걸 정의
    main(sys.argv) # sys.argv = terminal을 통해 인자값을 받을 수 있도록 명령
from bs4 import BeautifulSoup
import pandas as pd
import requests

def crwaling(code, total_page):
    # url 조합
    front_url = "http://movie.naver.com/movie/point/af/list.nhn?st=mcode&sword="
    back_url = "&target=after&page="
    url_base = front_url + str(code) + back_url

    re = []
    for i in range(1, total_page + 1):
        url = url_base + str(i)

        res = requests.get(url) # 접근 요청
        soup = BeautifulSoup(res.text, 'lxml') # 데이터들 중에서 텍스타만 가져와 lxml로 저장

        score_result = soup.select('.list_netizen .title ')

        # 불필요한 텍스트 및 앞뒤 공백 제거
        for i in score_result:
            i.find(class_='movie').extract() # movie color_b 클래스지만 띄어쓰기를 무시하고 movie만으로도 충분히 인식
            i.find(class_='report').extract() # report 클래스 제거
            re.append(i.text.strip())

    return re

def main():
    code = 146485
    total_page = 20

    df = pd.DataFrame(crwaling(code, total_page))
    print(df)

    df.to_csv('out.csv')

main()

댓글