닫기

PROFESSIONAL AI DEVELOPER CHAGAUN

업무자동화 솔루션

클리커 레시피

HOME 업무자동화 솔루션 클리커 레시피
[숏폼도전_01]해외 최신 뉴스 수집하기
2022.10.23

안녕하세요, 업무자동화툴(RPA툴) 클리커 운영자입니다.


클리커를 통해 업무자동화(RPA)를 위한 다양한 레시피를 만들어 공개를 하고 있는데요


오늘은 숏폼 제작을 위한 첫번째 단계로 해외 유명 사이트로부터 최신 뉴스를 수집하여 네이버 카페에 올리고

또한 csv 파일로 저장해 보는 샘플을 만들어 보았습니다.


뉴스를 수집하기 위한 절차는 다음과 같습니다.


1. 먼저 뉴스에서 수집하고자 하는 키워드를 정합니다. 수집하고자 하는 페이지에서 해당 키워드가 들어 있는 뉴스만을 스크래핑하여 가져올 것이기 때문입니다. 여기에서는 한국 또는 북한과 관련한 뉴스만을 수집해 보고자 합니다. 그래서 키워드를 'Korea'로 정해 보았습니다.


2. 특정 사이트에서 뉴스를 수집하기 위해서는 해당 사이트에 접속하여 키워드와 매칭이 되는 뉴스만을 수집해야 하는데요. 여기에서는 CNN 사이트의 Asia 코너에서  'CNN Breaking News' 영역만을 반복적으로 크롤링하여 최신 뉴스를 가져오는 레시피를 만들어 사용해 보고자 합니다.


3.  'CNN Breaking News' 영역을 크롤링하는 레시피를 만들어 클리커에 탑재 한 후 스케줄링 잡을 만들어 10초 간격으로 하루종일 모니터링을 하여 'korea' 라는 키워드가 들어간 뉴스가 올라온 경우 자동으로 스크래핑 해 보도록 하겠습니다.


4. 수집된 데이터를 네이버 클리커 카페에 자동으로 올리고 또한 csv 파일로 피씨에도 저장해 보도록 하겠습니다.


여기에서 작업한 레시피는 클리커 → 레시피 코너와 네이버 → 카페에 올리도록 하겠습니다. 아래의 링크를 통해 확인해 볼 수 있을 것입니다.


클리커->레시피     네이버 카페 클리커



1. 다음은 'CNN Breaking News' 를 수집하는 레시피를 탑재한 클리커 캡쳐 화면입니다.





2. 다음은 클리커에서 설정한 스케줄링 잡 화면을 캡쳐한 것입니다. '클리커 → 도구 → 설정' 클릭을 통해 스케줄링 설정을 할 수 있습니다.




=> 10초 단위로 반복적으로 수행이 되는데요 '작업 시작' 클릭 후 10초 후에 처음 작업이 시작되며 현재의 작업이 끝난 후 10 초 후에 다시 반복적으로 수행이 됩니다.


스케줄링 설정 방법은 차가운->도움말 코너에 잘 나와 있습니다.


3. 다음은  'CNN Breaking News' 레시피 파일을 캡쳐한 내용입니다.


{
    "0": {
        "0": {
            "unit_index": 0,
            "line_task_name": "CNN_BREAKING_NEWS"
        },
        "1": {
            "unit_index": 1,
            "combo_search_site": "https://edition.cnn.com/asia",
            "check_auto_paste": false
        },
        "2": {
            "unit_index": 2,
            "line_filter_type": 0,
            "combo_filter_tag": "div",
            "combo_filter_attr": "data-analytics",
            "combo_filter_op": "EQ",
            "combo_filter_item": "Asia_grid-small_article_"
        },
        "3": {
            "unit_index": 3,
            "line_filter_type": 1,
            "combo_filter_tag": "a",
            "combo_filter_attr": "href",
            "combo_filter_op": "LIKE",
            "combo_filter_item": "index.html"
        },
        "4": {
            "unit_index": 11,
            "plain_scripts": "# 검색을 위해 사용할 키워드 목록\nkeyword_list = ['Korea', 'Indonesia']\nkeyword_list = [keyword.lower() for keyword in keyword_list]\n\n# 기존 추출된 데이터 읽기\nline_task_name = u0.ID['line_task_name']\nfile_name = '@OPATH' + '\\\\' + line_task_name + '.csv'\n\ncsv_title_list = list()\ncsv_df = pd.DataFrame(columns=['create_date', 'url', 'title', 'body'])\nif os.path.exists(file_name):\n\tcsv_df = pd.read_csv(file_name, sep='\\t')\n\tcsv_title_list = csv_df['title'].to_list()\n\nprint('기존(csv)건수:', len(csv_title_list))\n",
            "dynamic_plain_scripts_vscroll": 10
        },
        "5": {
            "unit_index": 11,
            "plain_scripts": "# 엘러먼트상에서 검색어의 조건에 맞는 기사 타이틀 추출\narticle_dict = dict()\nsatisfied_title = False\nfor ii, element in enumerate(reversed(list(u3.el))):\n\ttitle = element.text.replace('\\t', '    ').strip()\n\tif len(title) <= 0: \n\t\tu3.el.remove(element)\n\t\tcontinue\n\n\t# 검색어 키워드를 가지고 있는 얼러먼트 찾기\n\tsatisfied_title = False\n\tfor keyword in u4.keyword_list:\n\t\tif title.lower().find(keyword) >= 0:\n\t\t\tsatisfied_title = True\n\n\t# 중복된 엘러먼트 재거\n\turl = element.get_attribute('href')\n\tif satisfied_title and url not in list(article_dict.keys()) and title not in u4.csv_title_list:\n\t\tarticle_dict[url] = title\n\telse:\n\t\tu3.el.remove(element)\n\nprint('신규건수:', len(u3.el), satisfied_title)\n",
            "dynamic_plain_scripts_vscroll": 17
        },
        "6": {
            "unit_index": 11,
            "plain_scripts": "if len(u3.el) > 0:\n\t@CB= u3.el[0].get_attribute('href')\n\t@BROWSER.execute_script(\"window.open();\")\n\t@BROWSER.switch_to_window(@BROWSER.window_handles[-1])\n\tu3.el.pop(0)\nelse:\n\t@CURNO = 22\n\nprint('남은건수:', len(u3.el), 'cur_no:', @CURNO)",
            "dynamic_plain_scripts_vscroll": 6
        },
        "7": {
            "unit_index": 1,
            "combo_search_site": "https://edition.cnn.com/2022/10/20/asia/indonesia-cough-syrup-ban-child-deaths-intl-hnk/index.html",
            "check_auto_paste": true
        },
        "8": {
            "unit_index": 11,
            "plain_scripts": "# 기사 내용 추출\narticle_body = str()\nelements= @BROWSER.find_elements_by_class_name('article__content')\nif len(elements) > 0:\n\tarticle_body = elements[0].text.replace('\\t', '    ')\n",
            "dynamic_plain_scripts_vscroll": 3
        },
        "9": {
            "unit_index": 11,
            "plain_scripts": "# 날자, 타이틀, 본문을 csv에 저장\narticle_url = @CB\narticle_title = u5.article_dict.get(article_url, '')\ndata_list = [datetime.now().strftime('%Y-%m-%d %H:%M:%S'), article_url, article_title, u8.article_body]\nu4.csv_df.loc[len(u4.csv_df)] = data_list\nu4.csv_df.to_csv(u4.file_name, sep='\\t', index=False)\n",
            "dynamic_plain_scripts_vscroll": 5
        },
        "10": {
            "unit_index": 9,
            "line_time_break": "2",
            "line_time_script": "# 네이버-클리커 카페에 기사 올리기",
            "check_endof_task": false
        },
        "11": {
            "unit_index": 1,
            "combo_search_site": "https://cafe.naver.com/ca-fe/cafes/30664480/menus/5/articles/write?boardType=L",
            "check_auto_paste": false
        },
        "12": {
            "unit_index": 2,
            "line_filter_type": 0,
            "combo_filter_tag": "textarea",
            "combo_filter_attr": "class",
            "combo_filter_op": "EQ",
            "combo_filter_item": "textarea_input"
        },
        "13": {
            "unit_index": 11,
            "plain_scripts": "@CB = u9.article_title\n",
            "dynamic_plain_scripts_vscroll": 0
        },
        "14": {
            "unit_index": 4,
            "check_auto_peste": true,
            "plain_keywords": "Indonesia bans sale of all cough syrups after 99 child deaths",
            "combo_keyword_type": "한번에 모두",
            "general_unit_widget_height": 100,
            "general_plain_keywords_height": 56
        },
        "15": {
            "unit_index": 2,
            "line_filter_type": 0,
            "combo_filter_tag": "div",
            "combo_filter_attr": "data-a11y-title",
            "combo_filter_op": "EQ",
            "combo_filter_item": "본문"
        },
        "16": {
            "unit_index": 11,
            "plain_scripts": "@CB = u8.article_body",
            "dynamic_plain_scripts_vscroll": 0
        },
        "17": {
            "unit_index": 4,
            "check_auto_peste": true,
            "plain_keywords": "Jakarta, Indonesia\nCNN\n\nIndonesia has halted the sale of all syrup and liquid medicines following the deaths of nearly 100 children and an unexplained spike in cases of acute kidney injuries.\nThe ban, announced by the country’s Health Ministry on Wednesday, will remain until authorities complete an investigation into unregistered medical syrups suspected of containing toxic ingredients.\nHealth Ministry spokesperson Mohammad Syahril said 99 deaths and 206 cases of acute kidney injuries in children, mostly under the age of 6, were being investigated.\nAd Feedback\n“As a precaution, the ministry has asked health workers in health facilities not to prescribe liquid medicine or syrup temporarily,” he said. “We also ask that drug stores temporarily stop all sales of non-prescription liquid medicine or syrup until our investigations are completed.”\nThe ban comes after the World Health Organization (WHO) linked four Indian-made cough syrups to the deaths of up to 70 children suffering acute kidney failure in The Gambia, West Africa. Earlier this month Indian authorities shut down a factory in New Delhi where the medicines were made.\nWHO suspects that four of the syrups made by Maiden Pharmaceuticals Limited – Promethazine oral solution, Kofexmalin baby cough syrup, Makoff baby cough syrup and Magrip N cold syrup – contained “unacceptable amounts” of chemicals that could damage the brains, lungs, livers and kidneys of those who take them.\nADVERTISEMENT\nAd Feedback\nChild deaths in Gambia linked to cough syrups made in India, says WHO\nThe syrups being used in The Gambia were not available in Indonesia, according to the Southeast Asian country’s food and drugs agency.\nHowever, on Thursday, Indonesian Health Minister Budi Gunadi Sadikin said ethylene glycol and diethylene glycol – which are more usually found in products like antifreeze, paints, plastics and cosmetics – had been detected in syrups found in the homes of some child patients.\n“(The chemicals) should not have been present,” Budi said.\nHe added that the number of acute kidney failure cases could be higher than reported and his ministry was taking a conservative approach by banning the sale of all syrups.",
            "combo_keyword_type": "한번에 모두",
            "general_unit_widget_height": 100,
            "general_plain_keywords_height": 56
        },
        "18": {
            "unit_index": 2,
            "line_filter_type": 0,
            "combo_filter_tag": "a",
            "combo_filter_attr": "class",
            "combo_filter_op": "EQ",
            "combo_filter_item": "BaseButton BaseButton--skinGreen size_default"
        },
        "19": {
            "unit_index": 5,
            "combo_key_click_key": "Mouse.CLICK",
            "line_offset_xpos": "0",
            "line_offset_ypos": "0",
            "line_key_wait": "2",
            "line_key_repeat": "1"
        },
        "20": {
            "unit_index": 5,
            "combo_key_click_key": "Keys.Backward",
            "line_offset_xpos": "0",
            "line_offset_ypos": "0",
            "line_key_wait": "1",
            "line_key_repeat": "1"
        },
        "21": {
            "unit_index": 9,
            "line_time_break": "1",
            "line_time_script": "# 다음 기사가 있는 경우 u3으로 점프",
            "check_endof_task": false
        },
        "22": {
            "unit_index": 10,
            "line_left_side": "len(u3.el)",
            "combo_operator": ">",
            "line_rigt_side": "0",
            "line_jump_number": "6",
            "line_jump_total": "9999"
        },
        "23": {
            "unit_index": 9,
            "line_time_break": "10",
            "line_time_script": "# 레시피의 끝",
            "check_endof_task": true
        },
        "24": {
            "unit_index": 11,
            "plain_scripts": "print(u9.article_title)",
            "dynamic_plain_scripts_vscroll": 1
        }
    }
}


=> 레시피 내용을 유닛 인스턴스 단위로 간략하게 설명하면 다음과 같습니다.


참고로 네이버의 카페에 글을 쓰기 위해서는 클리커 브라우저에서 네이버 홈에 가신 후 가지고 있는 네이버 아이디로 먼저 로그인을 해 놓아야 합니다.


1. 검색하고자 하는 사이트 'https://edition.cnn.com/asia' 로 이동합니다.




2. 위의 페이지로부터 'CNN Breaking News' 영역의 뉴스 목록을 찾기 위해 메인태그를 통해 'CNN Breaking News' 영역이 속한 엘러먼트들을 찾습니다. 


여기에서 말하는 엘러먼트에 대한 지식이 필요한 분들은 구글에서 'selenium 엘러먼트' 같은 키워드로 검색해 보시면 자세한 내용을 확인하실 수 있습니다.



=> 'div' 태그의 'data-analytics' 어트리뷰트의 값이 'Asia_grid-small_article_' 인 얼러먼트를 찾습니다.

'CNN Breaking News'의 뉴스 목록이 들어 있는 얼러먼트들을 확인하실 수 있습니다.



3. 위의 2번에 있는 메인 태그 하위에 속한 엘러먼트들 중에 뉴스의 상세 내용이 들어 있는 엘러먼트들을 찾습니다.



=> 메인태그를 통해 찾은 엘러먼트들 중에서 'a' 태그의  'href'라는 어트리뷰트의 값에서 'index.html'을 포함하는 엘러먼트를 찾습니다.



4. 검색하고자 하는 키워드 목록을 설정하고, 이전 스케줄링을 통해  수집하여 저장해 놓은 csv 파일을 읽어들입니다.





5. u3에서 찾은 엘러먼트들로부터 검색어 조건에 맞는 엘러먼트만 남기고 나머지는 재거합니다.



=> 검색하고자 하는 키워드를 포함하고 있지 않은 뉴스를 포함한 엘러먼트나 중복항목들을 재거합니다.



6. 추출할 기사 내용을 수집하기 위해 상세 페이지를 열기 위해 부라우저의 새로운 탭을 열고 새로운 탭으로 전환합니다.




=> 브라우저의 현재 활성화된 탭이 아닌 새로운 탭을 열어 여기에서 뉴스 상세 페이지를 열기 위해 새로운 탭을 열어 여기로 이동합니다.



7. 기사 내용을 수집하기 위해 새로 열린 탭에서 상세 페이지를 오픈합니다.




=> 상세 페이지가 새로운 탭에서 오픈됩니다.



8. 해당 페이지로부터 기사 내용을 추출합니다.





9. 수집된 날짜, 기사 타이틀, 기사 내용을 모아 csv 파일로 저장합니다.





11.  네이버 카페 '클리커' 페이지를 오픈합니다.

위에서 설명드린데로 네이버 카페에 글을 쓰기 위해서는 네이버에 로그인이 되어 있어야 합니다.




12. 오픈된 페이지로부터 '제목' 엘러먼트를 찾습니다.




13. 위의 u9에서 구한 기사 제목을 클립보드에 저장합니다.





14. 클립도드에 저장된 내용을 '제목' 엘러먼트에 푸시하여 값을 씁니다.


=>클립보드로부터 값을 가져와 사용하기 위해서는 'Paste'를 체크합니다.



15. 이번에는 '본문' 엘러먼트를 찾습니다.




16. 위의 u8에서 구한 기사 본문 데이터를 클립보드에 저장합니다.




17. 클립보드로부터 기사 본문을 '본문' 엘러먼트에 씁니다.


=>한꺼번에 모두를 선택합니다. 그리고 클립보드로부터 데이터를 가져오기 위해서 'Paste'를 체크합니다.



18. '등록' 엘러먼트를 찾습니다.




19. '등록' 버튼을 클릭하여 기사를 네이버 카페 '클리커'에 저장합니다.




20. 새로 오픈했던 브라우저 탭을 닫습니다.





22. 다음 엘러먼트가 있는 경우 u6 으로 점프를 하여 반복 작업을 합니다.




반면에 더 이상 검색된 엘러먼트가 없는 경우 이번 작업을 끝냅니다. 



'[숏폼도전_01]해외 최신 뉴스 수집하기' 를 수행하는 절차는 다음과 같습니다.


1. 차가운 홈 페이지(https://chagaun.net)에 가셔서 클리커를 다운로드 받습니다.


2. 설치 후 바탕화면에 생성된 클리커 아이콘 실행합니다. 클리커를 실행합니다. 처음 클리커를 실행하게 되면 클리커 최신 버전이 자동으로 패치가 됩니다.


3. 이 페이지의  하단에 첨부된 '[숏폼제작_01]해외최신뉴스수집_CNN_Breaking_News_xxxxxx.json' 레시피를 다운로드 한 후 아래의 폴더에 가져다 놓습니다.


c:\chagaun\klicker\data\recipe


4. 클리커를 싱행하여 상단에 있는  '로드'  버튼을 클릭하여 위에서 다운로드 받은 파일을 탑재합니다.


5. 클리커 상단에 있는 '로그인' 버튼을 클릭하여 로그인을 합니다. 회원 가입을 하지 않은 경우 차가운 홈페이지(https://chagaun.net)에서 회원가입을 할 수 있습니다.


6. 로그인을 한 후 옆에 있는 '작업 시작' 버튼을 클릭하여 데이터 수집 작업을 시작합니다.


10초 후부터 반복적으로 'CNN Breaking News' 를 지속적으로 모니터링하여 'Korea'와 관련한 뉴스가 올라온 경우 자동으로 수집하여 c:\Chagaun\Klicker\data\outputs\CNN_BREAKING_NEWS.csv 파일에 저장이 됩니다.


또한 네이버 카페 '클리커' 의 '뉴스 → 숏폼제작' 코너에 올려 놓습니다.


지금까지 CNN으로부터 최신 뉴스를 수집하는 샘플 레시피를 만들어 보았는데요. 다음은 레딧, 트위터와 같은 다른 플랫폼으로부터도 데이터를 수집하는 부분을 추가해 보겠습니다.


아마도 수집된 데이터는 Open AI API를 통해 적절한 크기의 내용으로 문서를 요약한 후 다시 한국어로 번역하는 API(Clover or Google Translate)를 통해 한국어로 번역을 하는 순서로 진행이 되지 않을까요


잘 이해가 안되는 경우 아래의 이메일이나 클리커 홈(https://chagaun.net)를 통해 문의하시면 됩니다.


chagaunnet@gmail.net

010-3563-5530


이상입니다.


data/2022/10/25/숏폼제작_01해외최신뉴스수집_CNN_Breaking_News_221022.json

전체목록