본문 바로가기
Python

[Python] BeautifulSoup 으로 크롤링하기

by 슈퍼닷 2019. 11. 10.
반응형
table = soup.a # a태그 하나 찾음.

table = soup.find('div',{'id' : 'perfect'})
text = table.a.get_text()  # table에서 a태그인걸 찾고, 그걸 string으로 변환시킴.

일단 BeautifulSoup를 import하고..

from urllib.request import urlopen
from bs4 import BeautifulSoup as bs

 

BeautifulSoup 객체를 만들자.

url = "주소" # http://www.naver.com 같은거 
html = urlopen(url)
source = html.read()
html.close()

soup = bs(source, "html5lib") # BeautifulSoup 객체생성

 

1. find : 먼저 나오는 순서대로 조건에 해당하는 태그를 한개 찾음.

table = soup.find('tbody')  # tbody태그에 해당하는거 한개를 찾음.
table = soup.find('div', {'class' : 'main_body'}) # div태그이면서 class = main_body인거 한개찾음.
table = soup.find(class_='main_body') # main_body class 한개 찾기.
table = soup.find(id = 'main') # id = main 인거 한개 찾기.

2. find_all : 조건 맞는대로 리스트로 반환.

table = soup.find_all('div',{'class' : 'zz'})

for data in table:
	t = data.a.get("href") # a태그인곳에서 href="..." 부분에서 ...부분 가져오기

3. soup.tag

table = soup.a # a태그인거 하나 찾기

table = soup.find('div', {'id' = 'perfect'})
text = table.a.get_text() # table에서 a에 해당하는 html을 string으로 변환

 

 

이것만 알아도 쉽게 파싱하는것같다.

 

 

반응형

댓글