pip install beautifulsoup4
from bs4 import BeautifulSoup
html = '<h1 id="title">한빛출판네트워크</h1><div class="top"><ul class="menu"><li><a href="http://www.hanbit.co.kr/member/login.html" class="login">로그인</a></li></ul><ul class="brand"><li><a href="http://www.hanbit.co.kr/media/">한빛미디어</a></li><li><a href="http://www.hanbit.co.kr/academy/">한빛아카데미</a></li></ul></div>'
soup = BeautifulSoup(html, 'html.parser')
print(soup.prettify())
: 3에서는 분석할 HTML의 실제 웹페이지를 사용하지 않고 html 구조를 작성한 문자열을 사용한다.
: BeautifulSoup을 사용하기 위해 4에서 객체를 생성한다.
: BeautifulSoup() 생성자 함수의 첫 번째 매개변수로는 분석할 HTML을 저장한 문자열 객체인 html을 지정하고 두 번째 매개변수로는 사용할 분석기를 지정한다.
: 5에서 prettify() 함수를 사용하여 객체 soup에 저장된 내용을 HTML 문서 형태로 출력하여 확인한다.
>>> soup.h1
>>> tag_h1 = soup.h1
>>> tag_h1
>>> tag_div = soup.div
>>> tag_div
>>> tag_ul = soup.ul
>>> tag_ul
>>> tag_li = soup.li
>>> tag_li
>>> tag_a = soup.a
>>> tag_a
>>> tag_ul_all = soup.find_all("ul")
>>> tag_ul_all
>>> tag_li_all = soup.find_all("li")
>>> tag_li_all
>>> tag_a_all = soup.find_all("a")
>>> tag_a_all
>>> tag_a.attrs
>>> tag_a['href']
>>> tag_a['class']
>>> tag_ul_2 = soup.find('ul', attrs={'class':'brand'})
>>> tag_ul2
>>> title = soup.find(id="title")
>>> title
>>> title.string
>>> li_list = soup.select("div>ul.brand>li")
>>> li_list
>>> for li in li_list:
print(li.string)
: 웹 페이지를 크롤링하기 전에 크롤링 허용 여뷰를 확인하기 위해 주소 창에 '크롤링한 주소/robots.txt'를 입력해본다.
: robots.txt는 검색 엔진이나 웹 크롤러 등의 웹 로봇이 사이트를 방문했을 때 사이트의 수집 정책을 알려주기 위해 사용한다.
: robots.txt 파일이 없다면 수집 크롤링 가능
표시 | 허용 여부 |
---|---|
User-agent: Allow: / 또는 User-agent: Disallow: | 모든 접근 허용 |
User-agent:* Disallow: / | 모든 접근 금지 |
User-agent:* Disallow: /user/ | 특정 디렉토리만 접근 금지 |
: 할리스커피의 전국 매장 정보를 크롤링
from bs4 import BeautifulSoup
import urllib.request
result = []
for page in range(1,59):
Hollys_url = 'https://www.hollys.co.kr/store/korea/korStore.do?pageNo=%d&sido=&gugun=&store=' %page
print(Hollys_url)
html = urllib.request.urlopen(Hollys_url)
soupHollys = BeautifulSoup(html, 'html.parser')
tag_tbody = soupHollys.find('tbody')
for store in tag_tbody.find_all('tr'):
if len(store) <= 3:
break
store_td = store.find_all('td')
store_name = store_td[1].string
store_sido = store_td[0].string
store_address = store_td[3].string
store_phone = store_td[5].string
result.append([store_name]+[store_sido]+[store_address]+[store_phone])
>>> len(result)
>>> result[0]
>>> result[565]
>>> store_td
>>> store_td[1].string
>>> store_td[0].string
>>> store_td[3].string
>>> store_td[5].string
pip install pandas
import pandas as pd
hollys_tbl = pd.DataFrame(result, columns=('store', 'sido-gu', 'address', 'phone'))
hollys_tbl.to_csv('./6장_data/hollys1.csv', encoding='cp949', mode='w', index=True)
from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
import datetime
#[CODE 1]
def hollys_store(result):
for page in range(1,59):
Hollys_url = 'https://www.hollys.co.kr/store/korea/korStore.do?pageNo=%d&sido=&gugun=&store=' %page
print(Hollys_url)
html = urllib.request.urlopen(Hollys_url)
soupHollys = BeautifulSoup(html, 'html.parser')
tag_tbody = soupHollys.find('tbody')
for store in tag_tbody.find_all('tr'):
if len(store) <= 3:
break
store_td = store.find_all('td')
store_name = store_td[1].string
store_sido = store_td[0].string
store_address = store_td[3].string
store_phone = store_td[5].string
result.append([store_name]+[store_sido]+[store_address]+[store_phone])
return
#[CODE 0]
def main():
result = []
print('Hollys store crawling >>>>>>>>>>>>>>>>>>')
hollys_store(result) #[CODE 1] 호출
hollys_tbl = pd.DataFrame(result, colums=('store', 'sido-gu', 'address', 'phone'))
hollys_tbl.to_csv('./6장_data/hollys1.csv', encoding='cp949', mode='w', index=True)
del result[:]
if __name__ = '__main__':
main()