Conducting research on predicting corporate bankruptcies through news scraping.

We conducted news crawling for research on corporate bankruptcy prediction models using text mining. We will study prediction accuracy and performance using news text data.

6
Conducting research on predicting corporate bankruptcies through news scraping.

This post is one of the items discussed during the research on bankruptcy prediction model using text mining conducted by Hashscraper.

0. Overview

Based on similar previous studies, this research explores whether the accuracy of bankruptcy prediction can be improved by applying data such as news text in the prediction process, and whether the use of artificial intelligence enhances predictive performance.

1. Collecting raw data from online news sources

The raw data was set to news broadcasted between 2010 and 2021.

We adopted a method of crawling by searching for company names on the 'Naver News' platform.

However, there is one issue that needs to be addressed. Due to a large number of registered companies in South Korea and the vast amount of news data, collecting all news data within a set period is a challenging and time-consuming task. Therefore, it was important to collect the data as quickly and accurately as possible.

  • Time constraints

  • News data duplication issue

  • Data volume issue

  • Issue related to excluding advertisement news data

2. Progress of news data collection

Step-1. We decided to set up the collection process as follows.

notion image

notion image

Step-2. Writing the code

We wrote the code as shown below and will review it through testing.

column_ = ['기업', '기사발행일', '기사제목', '뉴스기사본문']
뉴스_df = pd.DataFrame(columns=column_)

driver = webdriver.Chrome()

회사명_ = 상폐기업['회사명']
종료연도_ = 상폐기업['종료연도']
종료월_ = 상폐기업['종료월']
종료일_ = 상폐기업['종료일']
시작연도_ = 상폐기업['시작연도']
시작월_ = 상폐기업['시작월']
시작일_ = 상폐기업['시작일']

# start = '2010.01.01'
# end = '2010.12.31'
# start_= '20100101'
# end_ = '20101231'

for 기업, 종료연도, 종료월, 종료일, 시작연도, 시작월, 시작일 in  zip(회사명_, 종료연도_, 종료월_, 종료일_, 시작연도_, 시작월_, 시작일_):

    start = (시작연도 + '.' + 시작월 + '.' + 시작일)
    end = (종료연도 + '.' + 종료월 + '.' + 종료일)
    start_= (시작연도 + 시작월 + 시작일)
    end_ = (종료연도 + 종료월 + 종료일)

    # 나중에 뉴스_df와 concat할 임시 df 생성 및 임시 리스트들 생성
    column_ = ['기업', '기사발행일', '기사제목', '뉴스기사본문']
    임시_df = pd.DataFrame(columns=column_)

    # 임시_df에 들어갈 리스트 생성
    본문리스트 = []
    날짜리스트 = []
    제목리스트 = []
    기업이름 = []

    # while 종료 조건으로 쓸 리스트 생성
    newslist = []
    datelist = []

    page = 1

    # 페이지수가 나와있지않으므로 맨끝에 page에 10씩더해서 계속 다음페이지로 이동
    # 20페이지 이후로는 광고 등 불필요한 기사가 많아 페이지를 20페이지로 한정한다.
    while page < 200:

        url = 'https://search.naver.com/search.naver?where=news&sm=tab_pge&query='+'"'+기업+'"'+'&sort=0&photo=0&field=0&pd=3&ds='+start+'&de='+end+'&cluster_rank=19&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:from'+start_+'to'+end_+',a:all&start='+str(page)'
        driver.get(url)

        response = requests.get(url)
        soup = BeautifulSoup(response.text, "lxml")

        # a태그중에서 class가 info인 것과 span태그에 class가 info 인 것 가져옴
        news_titles = soup.select("a.info")
        dates = soup.select('span.info')

        # 네이버기사와 신문사기사 둘다 하이퍼링크가 있을경우는 기사당 news가 2개씩 네이버 기사가 없을 경우는 1개씩만 링크가 추출된다
        # 어림잡아 news_titles수가 10개 미만일 경우는 기사의 수가 5개에서 10개 미만이라는 뜻으로 해석하여 10개 이상만 링크와 기사날짜를 추출
        if len(news_titles) >= 10:

            for news in news_titles:
                title = news.attrs['href']
                newslist.append(title)

            for date in dates:
                news_date = date.text
                datelist.append(news_date)

            # 네이버 검색시 page number가 다음페이지로 갈때마다 1, 11, 21 이렇게 10씩 더해지는데 다음페이지가 없을경우
            # 마지막 기사만을 포함한 같은 페이지를 계속 반환함. 따라서 기사와 날짜 둘 다 중복되서 저장될경우 종료함
            if (newslist[-1]==newslist[-2]) & (datelist[-1]==datelist[-2]):
                break

            page += 10

            time.sleep(1)

        # 기사수 5개 미만시 break, 기사없는기업 리스트에 저장함
        else:

            break

    # sid=101은 네이버 경제기사를 의미하는 듯함. 경제기사만 추출
    newslist = [news for news in newslist if 'sid=101' in news]

    # news_titles 뉴스기사 url 리스트가 존재시
    if news_titles:

        # 뉴스기사 url 자체에서는 text가 안가져와지는 특이사항 발생, 찾아보니 네이버기사는 인터넷에 떠야 페이지가 작동하는? 방식이라함
        # 셀레니움을 통해서 뉴스기사 url 주소로 창을 띄움
        for news in newslist:
            url = news
            driver.get(url)

            # 뉴스기사 url에서 본문과 제목, 기사작성날짜를 리스트에 저장함
            # 데이터프레임에 직접 행을 지정해주기는 번거로움..
            try:

                날짜 = driver.find_element('xpath', '//*[@id="ct"]/div[1]/div[3]/div[1]/div/span').text
                날짜리스트.append(날짜)

                제목 = driver.find_element('xpath', '//*[@id="ct"]/div[1]/div[2]/h2').text
                제목리스트.append(제목)

                본문 = driver.find_element('xpath', '//*[@id="dic_area"]').text
                본문리스트.append(본문)
                time.sleep(1)

                기업이름.append(기업)

            ## 로딩이 안되서 데이터를 못가져올 경우를 대비해 sleep 3초 주고 다시 시도
            except:

                time.sleep(3)

                try:

                    날짜 = driver.find_element('xpath', '//*[@id="ct"]/div[1]/div[3]/div[1]/div/span').text
                    날짜리스트.append(날짜)

                    제목 = driver.find_element('xpath', '//*[@id="ct"]/div[1]/div[2]/h2').text
                    제목리스트.append(제목)

                    본문 = driver.find_element('xpath', '//*[@id="dic_area"]').text
                    본문리스트.append(본문)
                    time.sleep(1)

                    기업이름.append(기업)

                # 그래도 데이터를 가져오지 못하는 경우는 페이지에 문제가 있다고 판단하여 PASS
                except:

                    pass

    # 혹시나 뉴스기사 url 리스트가 없을 경우는 pass
    else:
        pass

    # 기업별로 가져온 날짜와 본문, 제목, 기업이름을 임시 데이터프레임으로 저장
    임시_df.기사발행일 = 날짜리스트
    임시_df.뉴스기사본문 = 본문리스트
    임시_df.기사제목 = 제목리스트
    임시_df.기업 = 기업이름

    # 임시 데이터프레임을 뉴스 데이터프레임에 아래로 결합
    뉴스_df = pd.concat([뉴스_df, 임시_df])

# 앞에서 while 종료 조건이 같은 기사 2번저장인데 이럴 경우 중복으로 저장이 되야 종료되기때문에
# 중복기사 행 제거
뉴스_df.drop_duplicates(inplace=True)
뉴스_df.to_csv('../Step3_1_뉴스전처리/news/상폐기업뉴스.csv', index=None)

3. Challenges to face

The biggest challenge in developing a collection crawler is likely to be the server and speed.

When managing the server and speed personally, the following issues may arise, so be careful.

  1. Endless increase in processing time delay

  2. If using a single IP, a lot of traffic may lead to blocking issues

  3. If the channel is updated, maintenance costs may arise due to changes in HTML structure

You may have used various libraries and tried changing IPs using VPN. In situations where direct management is difficult or when a one-time big data construction is needed, considering the adoption of various solutions already available in the market may be more efficient in terms of productivity.

4. Points to be cautious about

The primary purpose of building big data is mostly for research purposes.

However, crawling is a technology that entrusts the initial data screening to machines rather than humans, so ethical and moral aspects should also be considered, not just technical issues.

Accessing sensitive data such as personal information requires a lot of caution. Therefore, all data collection should be done as transparently and fairly as possible.

Although this process may go unnoticed by some, it can make our research more valuable.

If you encounter difficulties in crawling, you can refer to our blog post or contact us for assistance.

Also read this post:

Data Collection, Automate Now

Start in 5 minutes without coding · Experience crawling 5,000+ websites

Get started for free →

Comments

Add Comment

Your email won't be published and will only be used for reply notifications.

Continue Reading

Get notified of new posts

We'll email you when 해시스크래퍼 기술 블로그 publishes new content.

Your email will only be used for new post notifications.