내가 한 노력들

2020-10-12 Python 과 Ruby Package Manager 본문

IT 공부/python

2020-10-12 Python 과 Ruby Package Manager

JONGI-N CHOI 2020. 10. 12. 10:31

 

 

Package Manager 사용해서 크롤러 만들기

<Python>

pip install requests

pip install requests

크롤링 하기위해서 cmd창에서 해당 명령어를 입력해서 requests를 install해준다.  

 

import requests
r = requests.get('https://github.com')
print(r.text)

improt로 requests를 불러오고 크롤링하고 싶은 홈페이지 주소를 입력해서 print로 출력해보면 

 

<a href="https://docs.github.com/en/github/site-policy/github-subprocessors-and-cookies">Learn more</a>
              </p>
            </div>
            <div class="text-right">
              <h5 class="text-blue">Always active</h5>
            </div>
          </div>

          <div class="d-md-flex flex-items-center py-3 border-top">
            <div class="f5 flex-1 mb-2 mb-md-0">
              <h5 class="mb-1">Analytics cookies</h5>
              <p class="f6 mb-md-0">We use analytics cookies to understand how you use our websites so we can make them better, e.g. they're used to gather information about the pages you visit and how many clicks you need to accomplish a task.
                <a href="https://docs.github.com/en/github/site-policy/github-subprocessors-and-cookies">Learn more</a>
              </p>
            </div>
            <div class="text-right">
              <div class="BtnGroup mt-1 mt-md-0 ml-2">
                <button class="btn btn-outline BtnGroup-item js-accept-analytics-cookies" type="button">Accept</button>
                <button class="btn btn-outline BtnGroup-item js-reject-analytics-cookies" type="button">Reject</button>
              </div>
            </div>
          </div>

해당 페이지의 모든 html 태그들을 확인할 수 있다. 

 

특정 태그나 class명의 태그의 내용만 크롤링하고 싶은경우??

pip install BeautifulSoup4

cmd창에서 해당 명령어를 입력해서 Beautifulsoup4를 install해준다.  

from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text, 'html.parser')
print('Title : '+ soup.title.string)
articles = soup.findAll('div',{'class' : 'text-right'})
print('Article : '+ articles[0].text)

위에서 크롤링한 r.text에서  title 속성이 string 인 것과 모든 div 태그에서 class가  'text-right'인 태그의 text내용을 불러오는 코드이다. 

Title : GitHub: Where the world builds software · GitHub
Article : Github

이런 식으로 특정 태그에 대한 정보를 가져올 수 있다. 

 

 

<참고자료 YOUTUBE - 생활코딩>

www.youtube.com/watch?v=2L8-lBbkDPI&list=PLuHgQVnccGMA0lO0qip6Phh6UL73TS0es&index=110&ab_channel=%EC%83%9D%ED%99%9C%EC%BD%94%EB%94%A9