컴퓨터 공부/👨‍💻 모각코

모각코 6회차 - 웹 스크래핑을 통한 정보 추출

letzgorats 2022. 11. 30. 18:50

 

모각코 마지막 회의 때는 각자 공부한 내용에 대해 소개하는 시간을 가졌습니다!

저는 웹 스크래핑을 통해 여러가지 정보를 가져오는 프로그램을 만들어봤습니다. 코드를 보면서 한 번 시작해볼까요~?

 

✏️ PART6. 웹 스크래핑

# Project ) 웹 스크래핑을 이용하여 IT뉴스와 오늘의 영어 회화, 최신 해외축구 뉴스를 가져와보자.
import re
import requests
from bs4 import BeautifulSoup


def create_soup(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"}
    res = requests.get(url, headers=headers)
    res.raise_for_status()
    soup = BeautifulSoup(res.text, "lxml")
    return soup


def print_news(index, title, link):
    print("{}. {}".format(index+1, title))
    print(" (링크 : {})".format(link))


def scrape_it_news():
    print("[IT 뉴스]")
    url = "https://news.naver.com/main/list.nhn?mode=LS2D&mid=shm&sid1=105&sid2=230"
    soup = create_soup(url)
    news_list = soup.find("ul", attrs={"class": "type06_headline"}).find_all(
        "li", limit=3)  # 3개 까지 가져오기
    for index, news in enumerate(news_list):
        a_idx = 0
        img = news.find("img")
        if img:
            a_idx = 1  # img 태그가 있으면 1번째 a 태그의 정보를 사용(기사 링크)

        a_tag = news.find_all("a")[a_idx]
        title = a_tag.get_text().strip()
        link = a_tag["href"]
        print_news(index, title, link)


def scrape_todaty_english():
    print("[오늘의 영어 회화]")
    url = "https://www.hackers.co.kr/?c=s_eng/eng_contents/I_others_english#;"
    soup = create_soup(url)
    sentences = soup.find_all("div", attrs={"id": re.compile("^conv_kor_t")})
    todaysExpression = soup.find_all("b", attrs={"class": "conv_txtTitle"})
    print()
    print("(영어 지문)")
    # 8문장이 있다고 가정할 때, index 기준 4~7까지 잘라서 가져오면 된다.
    print("<Today's expression>")
    print(todaysExpression[1].get_text())
    print()
    for sentence in sentences[len(sentences)//2:]:
        print(sentence.get_text().strip())
    # 8문장이 있다고 가정할 때, index 기준 0~3까지 잘라서 가져오면 된다.
    print()
    print("(한글 지문)")
    print("<오늘의 표현>")
    print(todaysExpression[0].get_text())
    print()
    for sentence in sentences[:len(sentences)//2]:
        print(sentence.get_text().strip())
    print()


def scrape_football_news():
    print("[오늘의 해외축구 뉴스]")
    print()
    url = "https://sports.news.naver.com/wfootball/index.nhn"
    soup = create_soup(url)
    news_list = soup.find("ul", attrs={"class": "home_news_list"}).find_all(
        "li")  # 3개 까지 가져오기
    news_list += soup.find("ul", attrs={"class": "home_news_list division"}).find_all(
        "li")  # 3개 까지 가져오기
    for index, news in enumerate(news_list):
        a_idx = 0
        img = news.find("img")
        if img:
            a_idx = 1  # img 태그가 있으면 1번째 a 태그의 정보를 사용(기사 링크)
        a_tag = news.find_all("a")[a_idx]
        title = a_tag.get_text().strip()
        link = "https://sports.news.naver.com"+a_tag["href"]
        print_news(index, title, link)


if __name__ == "__main__":
 
    scrape_it_news()  # IT 뉴스 정보 가져오기
    scrape_todaty_english()  # 오늘의 영어 회화 가져오기
    scrape_football_news()  # 해외축구 최신뉴스 가져오기

[IT 뉴스 정보 가져오기]

[오늘의 영어회화 정보 가져오기]

[오늘의 해외축구 뉴스 정보 가져오기]

웹 스크래핑을 통해서 매일 업데이트 되는 IT뉴스와 오늘의 영어회화 그리고 해외축구 뉴스를 얻을 수 있게 됐습니다!

beautifulsoup 라이브러리와 lxml 라이브러리, requests 라이브러리는 pip install을 통해 설치해주셔야 합니다!

정보를 끌어오시고 싶은 웹페이지의 DevTools를 킨 후, 적절한 값을 찾아주시면 원하시는 정보를 얻을 수 있을 거에요!

 

 

반응형