크롤링

크롤링_beautifulSoup

asu2880 2022. 6. 27. 12:31

beautifulSoup

- HTML 문서를 파이썬 객체로 변환하여 원하는 정보는 가져올 때 사용하는 라이브러리

from bs4 import BeautifulSoup as bs
# HTML 문서 -> 파이썬 객체로 변환
# 두번째
html = bs(res, 'lxml')
print(type(html))
print(type(res))

 

# find(tag name): tag name으로 요소객체를 접근
html.find('title').text

 

# 슬라이싱
html.find('title').text[:2]

 

# 공백 없애기
html.find('title').text.replace(' ', ' ')

 

html.find('a', {'class':'tit'}).text

 

# div.product_info: a.title
html.find('div', {'class':'product_info'}).find('a').text
html.find('div', {'class':'product_info'}).find('div').find('div').find('strong').text

# select_one(css 선택자): css 선택자를 이용해서 하나의 요소를 접근
html.select_one('div.product_info > a.title').text
html.select_one('div.product_info > div > div > strong').text 
# == html.select_one('div.price > strong').text

 

# select(css 선택자): css 선택자를 이용해서 여러개의 요소를 접근(리스트 반환)
# => findAll()와 같은 기능
titles = html.select('div.product_info > a.title')
prices = html.select('div.price > strong')

print(len(titles), len(prices))

 

for i in range(len(titles)):
    print(titles[i].text, prices[i].text)

728x90
반응형