안녕하세요.
요즘 할 일들이 많아서 일주일에 한번 글 쓰기가 소홀해졌네요.
오늘의 미션은
1. '한국타이어' 뉴스를 크롤링하라
2. 크롤링은 '매일' 오전 11시에 하고 싶다. 다음 게시글에서 작성하겠습니다!
한국타이어로 한 이유는 제가 주식을 사서... ㅎyㅎ
구글에서 진행 할 예정입니다. 그럼 시작해볼까요?
Python
크롤링에 사용할 것들을 설치하겠습니다.
pip install requests
pip install beautifulsoup4
먼저 우리가 가져와야하는 데이터를 확인해봐야겠죠?
구글로 이동합니다.
다들 크롤링 할 때 google.com 으로 할 것 입니다.
하지만 우리는 뉴스에 대한 데이터만 가져올 것 이기 때문에
news.google.com 을 가져오겠습니다.
그럼 한번 검색을 해봐야겠죠?
당연히 검색하면 잘 나올 것 입니다.
하지만 우리는 하루에 한번 데이터를 가져올 것 이기 때문에
2일, 7일, 한달 전 데이터는 필요하지 않습니다.
오직 오늘의 데이터만 필요한 것 입니다.

1일로 설정하고 뉴스를 가져오니
when:1d 가 검색창에 추가 된 것을 확인할 수 있고,
뉴스 게시글들도 하루치만 나오는 것을 확인할 수 있습니다.
그렇다면 우리는 when:1d 에 대해서 활용하면 될 것 입니다.

좋습니다.
이제 원하는 데이터는 뽑아봤고, 코드를 작성해볼까요?
import requests
from bs4 import BeautifulSoup
class tstation:
def __init__(self):
self.headers = {"Content-Type": "application/json"}
# +when:1d 는 하루 데이터
self.tstation = requests.get(url='https://news.google.com/search?q=한국타이어+when:1d&hl=ko&gl=KR&ceid=KR%3Ako')
def crawler(self):
html = self.tstation
soup = BeautifulSoup(html.text, 'html.parser')
bs = soup.select(
"#yDmH0d > c-wiz > div > div.FVeGwb.CVnAc.Haq2Hf.bWfURe > div.ajwQHc.BL5WZb.RELBvb"
)
# 뉴스의 제목만 가져온다.
answers = bs[0].findAll('h3', class_='ipQwMb ekueJc RD0gLb')
print(answers)

위 사진 오른쪽에 보이는 영역을 누르고,
마우스 오픈쪽 버튼 Copy > Copy selector 를 눌러주시면 됩니다.
그러면 복사가 되었고, 위의 코드처럼 넣어주시면 됩니다.
그럼 코드를 돌려볼까요?

뉴스데이터가 잘 들어있습니다!

본문까지는 필요가 없으니 제목과 클릭했을 때 접속할 수 있는 링크만 꺼내겠습니다.
자, 그러면 뉴스데이터는 확인했습니다.
그럼 이게 보여지는 게 중요하겠죠?
저는 Slack 을 사용해서 하루에 한번 크롤링 된 데이터를 출력하는 것을 구현하겠습니다.
Slack
import os, json, requests
from bs4 import BeautifulSoup
class tstation:
def __init__(self):
self.headers = {"Content-Type": "application/json"}
self.tstation = requests.get(url='https://news.google.com/search?q=한국타이어+when:1d&hl=ko&gl=KR&ceid=KR%3Ako')
# SLACK WEBHOOK 환경변수
self.slack_url = os.environ['SLACK_WEBHOOK']
def crawler(self):
html = self.tstation
soup = BeautifulSoup(html.text, 'html.parser')
bs = soup.select(
"#yDmH0d > c-wiz > div > div.FVeGwb.CVnAc.Haq2Hf.bWfURe > div.ajwQHc.BL5WZb.RELBvb"
)
answers = bs[0].findAll('h3', class_='ipQwMb ekueJc RD0gLb')
for answer in answers:
data = {
"attachments": [{
"color": "#36a64f",
"title": answer.text,
"title_link": f"https://www.news.google.com/{answer.find('a').get('href')}"
}]
}
requests.post(url=self.slack_url, headers=self.headers, data=json.dumps(data))
t = tstation()
t.crawler()
Slack WEBHOOK 은 환경변수로 설정하였습니다.
data = {} 아래보이는 값은 slack message를 설정할 수 있습니다.
저는 간단하게 title과 title_link를 가져왔습니다.
관련 링크 첨부하겠습니다.
https://api.slack.com/reference/messaging/attachments
Reference: Secondary message attachments
Another way to attach content to messages is the old attachments system. We prefer Block Kit now.
api.slack.com
사진과 같이 Slack 에 메시지가 작성되는 것을 확인할 수 있습니다!

https://github.com/2044smile/google-crawling-tstation
GitHub - 2044smile/google-crawling-tstation
Contribute to 2044smile/google-crawling-tstation development by creating an account on GitHub.
github.com
코드는 여기서 확인할 수 있고,
다음 게시글은 apscheduler 와 nohup를 이용하여
특정시간에 비동기적으로 돌아가는 것을 만들어보겠습니다.
감사합니다.
https://newbiecs.tistory.com/372
Python 구글 뉴스 데이터 크롤링(apscheduler, nohup) - 2
https://newbiecs.tistory.com/365 Python 구글 뉴스 데이터 크롤링(beautifulsoup4, slack) - 1 안녕하세요. 요즘 할 일들이 많아서 일주일에 한번 글 쓰기가 소홀해졌네요. 오늘의 미션은 1. '한국타이어' 뉴스를
newbiecs.tistory.com
'Language > Python' 카테고리의 다른 글
| Python 텔레그램(telegram) 채널 데이터 가져오기, Django Create a Model- 2 (0) | 2023.02.06 |
|---|---|
| Python 텔레그램(telegram) 설치(Installation), 로그인(Signing in), API 개발 도구(API development tools) - 1 (0) | 2023.01.30 |
| Save to AWS EFS(PVC) as AWS Lambda (2) | 2022.08.22 |
| Python argparse, S3 folder upload 폴더 업로드 (0) | 2022.07.16 |
| Python Lambda에 대해서 자세히 알아보자 (0) | 2021.04.17 |
댓글