Story of CowHacker

크롤링 본문

공부/Python

크롤링

Cow_Hacker 2021. 3. 30. 23:15
728x90

Python을 이용한 크롤링을 해보겠다.

 

이번 크롤링의 대상은 나의 블로그 사이트로 정했다.

 

 

 

 

 

내 블로그 메인 페이지다.

 

 

 

 

 

 

import requests               # HTTP 요청처리를 위해 사용하는 모듈이다.
from bs4 import BeautifulSoup # HTML 및 XML 파일에서 원하는 데이터를 손쉽게 Parsing 할 수 있는 Python 라이브러리다.

url = 'https://cowhacker.tistory.com/'     # 크롤링할 주소를 입력하는 구간이다.
response = requests.get(url)               # HTTP 요청처리를 GET방식으로 response라는 변수한테 주는 구간이다.
html = response.text                       # 응답을 읽고 텍스트를 반환하는 구간이다.
soup = BeautifulSoup(html, 'html.parser')  # 해당 값을 parser하는 구간이다.

print(soup)                                # pasrser한 것을 출력하는 구간이다.

위 코드가 불러오는 코드다.

이제 이것을 실행하면

 

** 혹시 requests랑 beautifulSoup가 설치되지 않았다면 구글링 해서 설치하자 **

 

 

 

 

 

 

 

<!DOCTYPE html>

<html lang="ko">
<head>
<link href="https://t1.daumcdn.net/tistory_admin/lib/lightbox/css/lightbox.min.css" rel="stylesheet" type="text/css"/><link href="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4/blogs/style/content/font.css?_version_=tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4" rel="stylesheet" type="text/css"/><link href="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4/blogs/style/content/content.css?_version_=tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4" rel="stylesheet" type="text/css"/><!--[if lt IE 9]><script src="https://t1.daumcdn.net/tistory_admin/lib/jquery/jquery-1.12.4.min.js"></script><![endif]--><!--[if gte IE 9]>
<!--><script src="https://t1.daumcdn.net/tistory_admin/lib/jquery/jquery-3.2.1.min.js"></script><!--<![endif]-->
<script src="https://t1.daumcdn.net/tistory_admin/lib/lightbox/js/lightbox-plus-jquery.min.js"></script>
<script>
lightbox.options.fadeDuration = 200;
lightbox.options.resizeDuration = 200;
lightbox.options.wrapAround = false;
lightbox.options.albumLabel = "%1 / %2";
</script>
<script>var tjQuery = jQuery.noConflict(true);</script><style type="text/css">.tt_article_useless_p_margin p {padding-top:0 !important;padding-bottom:0 !important;margin-top:0 !important;margin-bottom:0 !important;}</style><meta content="always" name="referrer"/><link href="//t1.daumcdn.net/tistory_admin/static/top/favicon_0630.ico" rel="icon"/><link href="//img1.daumcdn.net/thumb/C180x180/?fname=https%3A%2F%2Ftistory4.daumcdn.net%2Ftistory%2F3394828%2Fattach%2Ff6305f2ffde445629ead925067183141" rel="apple-touch-icon"/>
<link href="//img1.daumcdn.net/thumb/C76x76/?fname=https%3A%2F%2Ftistory4.daumcdn.net%2Ftistory%2F3394828%2Fattach%2Ff6305f2ffde445629ead925067183141" rel="apple-touch-icon" sizes="76x76"/>
<link href="//img1.daumcdn.net/thumb/C120x120/?fname=https%3A%2F%2Ftistory4.daumcdn.net%2Ftistory%2F3394828%2Fattach%2Ff6305f2ffde445629ead925067183141" rel="apple-touch-icon" sizes="120x120"/>
<link href="//img1.daumcdn.net/thumb/C152x152/?fname=https%3A%2F%2Ftistory4.daumcdn.net%2Ftistory%2F3394828%2Fattach%2Ff6305f2ffde445629ead925067183141" rel="apple-touch-icon" sizes="152x152"/><meta content="" name="description"/>
<!-- BEGIN OPENGRAPH -->
<link href="https://cowhacker.tistory.com" rel="canonical"><meta content="website" property="og:type"><meta content="https://cowhacker.tistory.com" property="og:url"><meta content="CowHacker" property="og:site_name"/><meta content="CowHacker" property="og:title"/><meta 
content="" property="og:description"/><meta content="https://tistory4.daumcdn.net/tistory/3394828/attach/f6305f2ffde445629ead925067183141" property="og:image"/>
<!-- END OPENGRAPH -->
<!-- BEGIN TWITTERCARD -->
<meta content="summary_large_image" name="twitter:card"/><meta content="@TISTORY" name="twitter:site"/><meta content="CowHacker" name="twitter:title"/><meta content="" name="twitter:description"/><meta content="https://tistory4.daumcdn.net/tistory/3394828/attach/f6305f2ffde445629ead925067183141" property="twitter:image"/>
<!-- END TWITTERCARD -->
<!-- BEGIN STRUCTURED_DATA -->
<script type="application/ld+json">{"@context":"http:\/\/schema.org","@type":"WebSite","url":"\/","potentialAction":{"@type":"SearchAction","target":"\/search\/{search_term_string}","query-input":"required name=search_term_string"}}</script>
<!-- END STRUCTURED_DATA -->
<meta charset="utf-8"/>
<meta content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width" name="viewport"/>        
<title>CowHacker</title>
<link href="https://cowhacker.tistory.com/rss" rel="alternate" title="CowHacker" type="application/rss+xml">
<link href="https://tistory4.daumcdn.net/tistory/3394828/skin/style.css?_T_=1575348789" rel="stylesheet"/>
<link href="https://tistory4.daumcdn.net/tistory/3394828/skin/images/font.css" rel="stylesheet"/>
<style>

                .wrap_sub {
                        background-image: url('https://tistory1.daumcdn.net/tistory/3394828/skinSetting/dbe75e7e678344df87df13bf51fcb10b');
                }

        </style>
<!--[if lt IE 9]>
        <script src="//t1.daumcdn.net/tistory_admin/lib/jquery/jquery-1.12.4.min.js"></script>
        <![endif]-->
<!--[if gte IE 9]><!-->
<script src="//t1.daumcdn.net/tistory_admin/lib/jquery/jquery-3.2.1.min.js"></script>
<!--<![endif]-->
<meta content="IP2MMOayNlk8sf_ieHhBTRnw7OYRUT1hRCvBmvLvStM" name="google-site-verification">
<style type="text/css">
                #daumSearchBox {
                        height: 21px;
                        background-image : url(//i1.daumcdn.net/imgsrc.search/search_all/show/tistory/plugin/bg_search2_2.gif);        
                        margin: 5px auto ;
                        padding: 0;
                }
                #daumSearchBox input {
                        background: none;
                        margin : 0;
                        padding : 0;
                        border : 0;
                }
                #daumSearchBox #daumLogo {
                        width: 34px;
                        height: 21px;
                        float: left;
                        margin-right: 5px;
                        background-image : url(//i1.daumcdn.net/img-media/tistory/img/bg_search1_2_2010ci.gif);
                }
                #daumSearchBox #show_q {
                        background-color: transparent;
                        border: none;
                        font: 12px Gulim, Sans-serif;
                        color: #555;
                        margin-top: 4px;
                        margin-right: 15px;
                        float: left;
                }

                #daumSearchBox #show_btn {
                        background-image : url(//i1.daumcdn.net/imgsrc.search/search_all/show/tistory/plugin/bt_search_2.gif);
                        width: 37px;
                        height: 21px;
                        float: left;
                        margin:0;
                        cursor:pointer;
                        text-indent:-1000em;
                }
        </style>
<link href="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4/blogs/plugins/TistoryProfileLayer/style.css?_version_=tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4" rel="stylesheet" type="text/css">
<script src="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4/blogs/plugins/TistoryProfileLayer/profile.js?_version_=tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4" type="text/javascript"></script>
<style type="text/css">
                .another_category { border: 1px solid #E5E5E5; padding: 10px 10px 5px; margin:10px 0; clear: both; }
                .another_category h4 { font-size: 12px !important; margin: 0 !important; border-bottom: 1px solid #E5E5E5 !important; padding: 2px 0 6px !important; }
                .another_category h4 a { font-weight: bold !important; }
                .another_category table { table-layout: fixed; border-collapse: collapse; width: 100% !important; margin-top: 10px !important; }
                * html .another_category table { width: auto !important; }
                *:first-child+html .another_category table { width: auto !important; }
                .another_category th, .another_category td { padding: 0 0 4px !important; }
                .another_category th { text-align: left; font-size: 12px !important; font-weight: normal;  word-break: break-all; overflow: hidden; line-height: 1.5; }
                .another_category td { text-align: right; width: 80px; font-size: 11px; }
                .another_category th a { font-weight: normal; text-decoration: none; border: none !important; }
                .another_category th a.current{ font-weight: bold; text-decoration: none !important; border-bottom: 1px solid !important; }
                .another_category th span { font-weight: normal; text-decoration: none; font: 10px Tahoma, Sans-serif; border: none !important; }

                .another_category_color_gray, .another_category_color_gray h4 { border-color: #E5E5E5 !important; }
                .another_category_color_gray * { color: #909090 !important; }
                .another_category_color_gray th a.current{border-color:#909090 !important;}
                .another_category_color_gray h4, .another_category_color_gray h4 a { color: #737373 !important; }


                .another_category_color_red, .another_category_color_red h4 { border-color: #F6D4D3 !important;  }
                .another_category_color_red * { color: #E86869 !important; }
                .another_category_color_red th a.current{border-color:#E86869 !important;}
                .another_category_color_red h4, .another_category_color_red h4 a { color: #ED0908 !important; }


                .another_category_color_green, .another_category_color_green h4 { border-color: #CCE7C8 !important; }
                .another_category_color_green * { color: #64C05B !important; }
                .another_category_color_green th a.current{border-color:#64C05B !important;}
                .another_category_color_green h4, .another_category_color_green h4 a { color: #3EA731 !important; }


                .another_category_color_blue, .another_category_color_blue h4 { border-color: #C8DAF2 !important; }
                .another_category_color_blue * { color: #477FD6 !important; }
                .another_category_color_blue th a.current{border-color:#477FD6 !important;}
                .another_category_color_blue h4, .another_category_color_blue h4 a { color: #1960CA !important; }


                .another_category_color_violet, .another_category_color_violet h4 { border-color: #E1CEEC !important;  }
                .another_category_color_violet * { color:#9D64C5 !important; }
                .another_category_color_violet th a.current{border-color:#9D64C5 !important;}
                .another_category_color_violet h4, .another_category_color_violet h4 a { color: #7E2CB5 !important; }
        </style>
<script type="text/javascript">

        window.TistoryBlog = {
            basePath: "",
            url: "https://cowhacker.tistory.com",
            tistoryUrl: "https://cowhacker.tistory.com",
                        manageUrl: 'https://cowhacker.tistory.com/manage',
            token: 'rQojTlTngUToRu3qaqKjAw=='
        };
        var servicePath = "";
        var blogURL = "";
    </script>
<script> (function() { window.orgjQuery = window.jQuery; window.jQuery = tjQuery })()</script>
<script defer="" src="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4/blogs/script/reaction/reaction-button-container.min.js?_version_=tistory-5bd58cc8d7b7dfbfb7f1002c26058b7a1e9fdce4" type="text/javascript"></script>   
<script> (function() { window.jQuery = window.orgjQuery; delete window.orgjQuery })()</script>
<script src="https://t1.d
[<strong class="tit_post">알리오올리오 파스타</strong>, <strong class="tit_post">로제파스타</strong>, <strong class="tit_post">한강</strong>, <strong class="tit_post">백준10757번 큰수 A + B</strong>, <strong class="tit_post">백준 16435번 스네이크버드</strong>, <strong class="tit_post">우분투 Apache2 기본 경로 변경</strong>, <strong class="tit_post">부트스트랩 CDN 테마</strong>, <strong class="tit_post">부트스트랩 CDN 사용법</strong>]

나의 블로그 메인 페이지 HTML을 모두 출력하는걸 볼 수 있다.

 

 

 

 

 

나는 이제 타겟을 블로그 제목들로 잡아 출력해볼 것이다.

 

 

 

 

 

 

F12번을 눌러 해당 제목은 어떤 Type이며 변수명을 썼는지 확인해본다.

 

 

 

 

 

import requests               # HTTP 요청처리를 위해 사용하는 모듈이다.
from bs4 import BeautifulSoup # HTML 및 XML 파일에서 원하는 데이터를 손쉽게 Parsing 할 수 있는 Python 라이브러리다.

url = 'https://cowhacker.tistory.com/'     # 크롤링할 주소를 입력하는 구간이다.
response = requests.get(url)               # HTTP 요청처리를 GET방식으로 response라는 변수한테 주는 구간이다.
html = response.text                       # 응답을 읽고 텍스트를 반환하는 구간이다.
soup = BeautifulSoup(html, 'html.parser')  # 해당 값을 parser하는 구간이다.

title = soup.find_all('strong',{'class':'tit_post'}) # strong이라는 Type에 tit_post라는 class를 불러와 title이라는 변수에 넣는다.

print(title)                                # pasrser한 것을 출력하는 구간이다.

추가된 부분은 9번째 줄이다.

title = soup.find_all('strong',{'class':'tit_post'})

이것인데 설명을 하자면

1. title이라는 변수에 soup는 아까 나의 블로그 메인 전체 페이지 라는걸 뜻하고

2. .find_all은 그 오른쪽 옆 괄호 안에 해당하는 녀석 모두를 찾아내겠다는 것이다.

   여기서 .find만 하면 모두가 아닌 첫 번째 녀석만 크롤링한다.

3. 괄호 안을 설명 하자면 strong이라는 Type에 tit_post라는 class를 불러온다는 것이다.

 

 

 

 

[<strong class="tit_post">알리오올리오 파스타</strong>, <strong class="tit_post">로제파스타</strong>, <strong class="tit_post">한강</strong>, <strong class="tit_post">백준10757번 큰수 A + B</strong>, <strong class="tit_post">백준 16435번 스네이크버드</strong>, <strong class="tit_post">우분투 Apache2 기본 경로 변경</strong>, <strong class="tit_post">부트스트랩 CDN 테마</strong>, <strong class="tit_post">부트스트랩 CDN 사용법</strong>]

출력 값은 위와 같은데 음... 머랄까 조잡하다.!!!

 

 

 

 

 

 

 

 

import requests               # HTTP 요청처리를 위해 사용하는 모듈이다.
from bs4 import BeautifulSoup # HTML 및 XML 파일에서 원하는 데이터를 손쉽게 Parsing 할 수 있는 Python 라이브러리다.

url = 'https://cowhacker.tistory.com/'     # 크롤링할 주소를 입력하는 구간이다.
response = requests.get(url)               # HTTP 요청처리를 GET방식으로 response라는 변수한테 주는 구간이다.
html = response.text                       # 응답을 읽고 텍스트를 반환하는 구간이다.
soup = BeautifulSoup(html, 'html.parser')  # 해당 값을 parser하는 구간이다.

title = soup.find_all('strong',{'class':'tit_post'}) # strong이라는 Type에 tit_post라는 class를 불러와 title이라는 변수에 넣는다.

for _ in title:
    print(_.text)                         # pasrser한 것을 출력하는 구간이다.

for문을 갑자기 내가 사용했는데

이유는 find_all이라는 녀석은 리스트 형식이 아니라 bs4.element.ResultSet형식이라 출력 옵션이 사용 불가하기 때문에

형식을 바꿔주려고 for문을 사용했다.

 

그리고. text이라는 print문에 옵션을 달아 줬는데 이것의 역할은 HTML안의 Value 값만 출력하겠다는 것이다.

 

 

 

 

 

그럼 위와 같이 딱 깔끔하게 Value값만 나오는 걸 볼 수 있다.

 

 

 

 

 

 

이까지 간단한 크롤링이었다.

 

728x90

'공부 > Python' 카테고리의 다른 글

파이썬_클래스  (3) 2021.06.06
파이썬_함수  (0) 2021.06.04
Comments