CSS Selector를 사용한 크롤링

이해하기 쉽고, 장황하지 않은 자료를 기반으로 강의를 진행합니다.
잔재미코딩 소식 공유
좀더 제약없이, IT 컨텐츠를 공유하고자, 자체 온라인 사이트와, 다음 두 채널도 오픈하였습니다
응원해주시면, 곧 좋은 컨텐츠를 만들어서 공유하겠습니다
●  잔재미코딩 뉴스레터 오픈 [구독해보기]
●  잔재미코딩 유투브 오픈 [구독해보기]

4. CSS Selector를 사용한 크롤링

In [ ]:
import requests
from bs4 import BeautifulSoup

res = requests.get('http://v.media.daum.net/v/20170615203441266')
soup = BeautifulSoup(res.content, 'html.parser')
In [ ]:
# 태그 검색
soup.find('title')

# select 함수는 리스트 형태로 전체 반환
title = soup.select('title')[0]
print (title)
print (title.get_text())
In [ ]:
# 띄어쓰기가 있다면 하위 태그를 검색
title = soup.select('html head title')[0]
print (title.get_text())
In [ ]:
# 띄어쓰기가 있다면 하위 태그를 검색
# 이때 바로 직계의 자식이 아니여도 관계없음
title = soup.select('html title')[0]
print (title.get_text())
In [ ]:
# > 를 사용하는 경우 바로 아래의 자식만 검색
# 바로 아래 자식이 아니기 때문에 에러 발생
title = soup.select('html > title')[0]
print (title.get_text())
본 자료 보다 업데이트된 자료와 함께 온라인 강의로 익히면 체계적으로 이해할 수 있습니다!
퀄러티가 다른 온라인 강의로 차근차근 익혀보세요
In [ ]:
# 바로 아래 자식을 검색
title = soup.select('head > title')[0]
print (title.get_text())
In [ ]:
# .은 태그의 클래스를 검색
# class가 article_view인 태그 탐색
body = soup.select('.article_view')[0]
print (type(body), len(body))
for p in body.find_all('p'):
    print (p.get_text())
In [ ]:
# div태그 중 class가 article_view인 태그 탐색
body = soup.select('div.article_view')[0]
print (type(body), len(body))
for p in body.find_all('p'):
    print (p.get_text())
In [ ]:
# div 태그 중 id가 harmonyContainer인 태그 탐색
container = soup.select('#harmonyContainer')
print (container)
In [ ]:
# div태그 중 id가 mArticle 인 태그의 하위 태그 중 아이디가 article_title인 태그
title = soup.select('div#mArticle  div#harmonyContainer')[0]
print (title.get_text())
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다
In [ ]:
import re

res = requests.get('http://media.daum.net/economic/')

soup = BeautifulSoup(res.content, 'html.parser')

# a태그이면서 href 속성을 갖는 경우 탐색, 리스트 타입으로 links 변수에 저장됨
links = soup.select('a[href]')
   
for link in links:
    # print (link) # <a class="link_services link_services2" href="http://sports.media.daum.net/sports">스포츠</a>
    # print (link['href']) # http://sports.media.daum.net/sports
    if re.search('http://\w+', link['href']):  # http:// 문자열 이후에 숫자 또는 문자[a-zA-Z0-9_]가 한 개 이상 있는 데이터와 매치됨 
        print (link['href'])

CSS Selector 활용 팁

  1. 네이버 부동산 매매 아파트 이름과 가격만 찾아보기
    • CSS Selector 를 활용하는 팁: Chrome F12(WINDOW) or Alt + Command + i(MAC) --> Copy Selector 참고
    • Copy Selector 시 일부 태그에 붙는 :nth-child(#) 은 동일한 태그로 리스트가 있을 경우, 리스트 중 특정한 값만 가리킴 . 전체 리스트를 가져오는 경우에는 :nth-child(#) 은 삭제할 필요가 있음
In [ ]:
import re
import requests
from bs4 import BeautifulSoup

res = requests.get('http://land.naver.com/article/divisionInfo.nhn?rletTypeCd=A01&tradeTypeCd=A1&hscpTypeCd=A01%3AA03%3AA04&cortarNo=1168000000&articleOrderCode=&cpId=&minPrc=&maxPrc=&minWrrnt=&maxWrrnt=&minLease=&maxLease=&minSpc=&maxSpc=&subDist=&mviDate=&hsehCnt=&rltrId=&mnex=&siteOrderCode=&cmplYn=')

soup = BeautifulSoup(res.content, 'html.parser')

# a 태그이면서 href 속성 값이 특정한 값을 갖는 경우 탐색
link_title = soup.select("#depth4Tab0Content > div > table > tbody > tr > td.align_l.name > div > a.sale_title")
link_price = soup.select("#depth4Tab0Content > div > table > tbody > tr > td.num.align_r > div > strong")

for num in range(len(link_price)):
    print(link_title[num].get_text(), link_price[num].get_text())