-- 01.BeautifulSoup 기본.ipynb --
Web Crawling
fp = open("simple.html", "r", encoding="utf-8")
html = fp.read()
fp.close()
from google.colab import drive
drive.mount('/content/drive')
html
from bs4 import BeautifulSoup
dom = BeautifulSoup(html, "html.parser")
#BeautifulSoup 생성자의 두번째 매개변수로는 html.parser 나 lxml 을 많이 사용한다. 여기서는 동일
type(dom)
#dom.select_one(CSS selector)
dom.select_one("h1")
type(dom.select_one("h1"))
dom.select_one("li")
dom.select(".fruit")
dom.select('xxx')
dom.select_one('xxx') # 못 찾으면 None 리턴
len(dom.select('.fruit'))
dom.select('.fruit')[0] # select 한 element 들 중 첫번째 리턴. 리스트 타입이므로 인덱스 사용
dom.select('.fruit')[0].text
dom.select('.fruit')[0].text.strip()
dom.select('.fruit')[1]
dom.select('.fruit')[1].text.strip()
dom.select_one('ul')
dom.select_one('ul').text # 내부의 text 들이 한덩어리로 리턴
result = []
for element in dom.select('.fruit') :
result.append(element.text.strip())
result
[e.text.strip() for e in dom.select('.fruit')]
dom.select_one()
items = dom.select("ol li")
items
items[0].select_one("a")
items[0].select_one("a").attrs # attrs는 dict리턴
items[0].select_one("a").attrs['href']
items[0].select_one("a").attrs.get('href')
[
{
'url' : item.attrs.get('href').strip(),
'link' : item.text.strip()
}
for item in dom.select('ol > li > a')
]
dom.select('ol > li > a')
element 를 dom 에서 제거
rows = dom.select_one("#books").select("tr")
rows
len(rows)
rows
<결과 예시>
[{'제목': '이것이 파이썬이다', '가격': '[도서] 19,200원'},
{'제목': '저것도 파이썬이다', '가격': '[할인] 12,800원'},
{'제목': '그래도 파이썬인가?', '가격': '[중고] 6,500원'}]
None
[
{
"제목" : element.select('td')[0].text.strip(),
"가격" : element.select('td')[1].text.strip(),
}
for element in rows
if element.select_one("td")
]
dom = BeautifulSoup(html, 'html.parser')
rows = dom.select_one('#books').select('tr')
result = []
for row in rows :
if row.select_one("td") :
price = row.select_one("td:nth-child(2)")
print('decimpose() 전', price)
price.select_one('b').decompose()
print('decimpose() 후', price)
item = {
"제목" : row.select_one("td:first-child").text.strip(),
"가격" : price.text.strip()
}
result.append(item)
result
19,200월 --> 19200
myStr = "1,232,200원"
myStr.replace(',','')
myStr.replace(',','')[:-1]
int(myStr.replace(',','')[:-1])
int(''.join([
ch
for ch in myStr
if '0' <= ch <= '9'
]))
import re
int(re.sub(r'\D', '', myStr))
dom = BeautifulSoup(html, 'html.parser')
rows = dom.select_one('#books').select('tr')
result = []
for row in rows :
if row.select_one("td") :
price = row.select_one("td:nth-child(2)")
print('decimpose() 전', price)
price.select_one('b').decompose()
print('decimpose() 후', price)
item = {
"제목" : row.select_one("td:first-child").text.strip(),
"가격" : int(price.text.strip().replace(',','')[:-1])
}
result.append(item)
result
import pandas as pd
pd.DataFrame(result)