본문 바로가기

MLOps/Development

미증권 뉴스 스크랩핑(Node.js , Express, Puppeteer, Koyeb)

미 증권 뉴스 스크랩핑 하기

푼돈으로 주식하는 서학개미로서, 주식 뉴스는 조금이라도 읽자라 생각해서 주식 블로그를 하고 있는데 블로그에 글이 올라가는 루틴은 아래와 같다


기사의 본문을 다 읽는 것이 아니라, 요약본을 읽는 정도이다.

2시간 정도 쓰는 것 같은데 이렇게 많이 쓰고 싶지는 않았고 시간을 좀 줄이고자 했다.

 

그래서 아래 2단계를 자동화하려고 했지만,


아쉽게도 착각한 게 있었다.

ChatGPT를 결제해서 쓰는데  API는 그냥 사용 가능한 줄 알았다. ㅋㅋㅋ (알고 보니 별도 요금)

 

스타터들에게  5$ 를 지원해 주는데. 이걸로는 택도 없다.

그래서 5$ 로 API를 얼마나 사용할 수 있나 계산을 해봤다.

(가격 측정은 1000 토큰(약 750단어) 당 가격이 지불된다.  1000토큰 당 가격은 0.02$)

 

아무튼 5달러로 250,000개 토큰을 사용 가능하고, 뉴스 당 600 토큰이라고 가정하면 416개 뉴스를 요약 가능함
Investing에 하루 뉴스가 100개 이상 나오니까,  4 일정도 사용가능하다.

 

결론 : ChatGPT API는 사용 안 하고, 내용만 스크랩핑 해서 수동 요약하기로 했음


1. 스크래핑 API (Puppeteer , Express, Koyeb)

아쉽게도 파이썬으로 크롤링이 안 돼서 아래 3가지를 사용했다.

  1. Node.js 라이브러리 Puppeteer 
  2. API 배포를 위한 Express
  3. 무료 호스팅 플랫폼 Koyeb

1. 1. 스크랩

코드를 공유하는 건 양심에 가책을 느껴서 못하겠고, 다들 할 수 있으니 안 해야겠다.

 

 ScrapeHref

  • 오늘자 뉴스만 가져오기 위해서 업데이트 시간에 'ago'가 있는 , href 만 가져옴

ScrapeText

  • 제목과 본문
async function scrapeHref(url, selector) {
	...
    while (shouldContinue) {
        const currentPageUrl = `${url}/${i}`;
        ...
            // Check if the date string contains the word "ago"
            if (!date.includes('ago')) {
                shouldContinue = false;
                break;
            }
            ...
            data.push({ href, date });
        }
        i++;
    }
}
async function scrapeText(url, selector) {
    const hrefs = await scrapeHref(url, selector);
    for (const { href, date } of hrefs) {
        data.push({ title, paragraphs, date });
    }
    return data;
}
module.exports = scrapeText;

app.js

  • 메인은 키 확인 정도만 해줬다.
app.post('/scrape', async (req, res) => {
    if (apiKey !== process.env.API_KEY) {
        return res.status(401).json({ error: 'Invalid API key' });
    }
    res.json(data);
});

2 배포

Heroku

처음엔 Heroku 많이 쓴다 길래, 바로 가입하고 설치할 것들 설치했다.

할 것들 다 하니까 갑자기 유료화 이슈가..


Koyeb

 

The fastest way to deploy applications globally

Koyeb is a developer-friendly serverless platform to deploy apps globally. No-ops, servers, and infrastructure management.

www.koyeb.com


Koyeb의 장점은 도커 이미지 파일로 배포 가능하다는 점이다.

근데 인스턴스 만드는데, 시간당 0.0072$?.. 바로 뒤로 가기 버튼을 눌러버리는 하남자 행동을 했다.

 

걱정할 필요가 없었다. 매달 5.5 달러를 준단다. 31일 사용하면 5.4$ 나오기 때문에 그냥 무료다.

 

배포시켰지만 추가 요금 나올까 봐 뭔가 찜찜..

 

리턴 예시

{'title': "China's Huawei partners with more automakers to produce Aito EVs",\
'paragraphs': ["SHANGHAI (Reuters) - China's Huawei Technologies is partnering with more legacy automakers to produce Aito-branded electric cars, the company's senior executive said on Saturday, in a move to expand its presence in the auto industry.", "Huawei will team up with Chery Automobile, BAIC Motor and Anhui Jianghuai Automobile Group in jointly developing and manufacturing Aito-branded vehicles, Richard Yu, Huawei's Smart Car CEO, said at the China EV 100 forum in Beijing.", 'Huawei, which has already a partnership with Seres Group to make Aito cars, plans a series of models including SUVs, sedans and multipurpose vehicles under the Aito brand, Yu added.', '"We\'d like to fully use the automakers\' resources of production capacity," Yu said.', "Seres sold a total of 80,000 Aito cars featuring Huawei's HarmonyOS system - developed by the company as an alternative to Android - in 2022, up more than six times from a year ago, according to company filings.", "Huawei's Chairman Eric Xu reiterated at a press conference on Friday that the company doesn't make cars on its own but only helps other automakers make better vehicles.", "Huawei has been hit by a series of export controls by Washington which says it is a security risk, which the company denies. The sanctions have blocked Huawei from buying key components as well as from using Google (NASDAQ:GOOGL)'s Android operating system.", '', "The sanctions have also affected Huawei's partnerships with global automakers, who have given up using Huawei's vehicle connectivity technologies in the past two years, Yu said on Saturday.", 'Tension with the U.S. saw Meng detained for three years in Canada over alleged efforts to cover up attempts by Huawei-linked companies to sell equipment to Iran in breach of U.S. sanctions.', '', ''],
'date': '-\xa022 hours ago'}

3. 스케줄링

  • 스케줄링은 깃허브 액션 돌려서 일 단위 Json 뽑고 GPT 선생님한테 물어보는 수작업까지 끝

 4. 죽어가는 노트북

과거에 노트북을 너무 가성비로 산 사람의 최후. 배포전에 wsl 위에서 하는데 속터져서 환장했다 그냥.

하둡, 스파크 친구들은 점점 더  잘 안 돌아간다.. 


5. 마무리

그놈의 스크래핑 또 했다. 

그래도 복사-붙여 넣기에서 시간 차이가 좀 나긴 해서 시간이 좀 줄어들 것이라고 예상한다.