본문 바로가기

데이터 사이언스 공부/파이썬으로데이터주무르기

chicago analysis

# 선요약

1. beautiful soup를 사용하여 웹크롤링을 할 수 있다. url를 읽어서 html 정보를 받으면 find, find_all로 element에 접근 가능하다.

2. tqdm으로 진행 상태를 확인할 수 있다. 

 

 

 

beautiful soup 사용하여 웹크롤링하는 예제

 

from bs4 import BeautifulSoup
page = open('./data/test_html.html', 'r').read()
soup = BeautifulSoup(page, 'html.parser')
(soup.prettify()) #들여쓰기로 보기좋게 출력
(list(soup.children)) #soup는 문서전체
html = (list(soup.children)[2]) #html 태그 안
(list(html.children)) #html의 children(body, title...) 보기
body = list(html.children)[3] #body 태그 안
(soup.body) #html안의 body 바로 찾기

(soup.find_all('p')) #모든 p태그 찾기
soup.find('p') #처음 p태그 하나만 찾기
soup.find_all(class_="outer-text") #클래스 이름으로 찾기
soup.find_all(id='first') #id 이름으로 찾기
body.p #body태그 안의 첫번째 p 찾기
body.p.next_sibling.next_sibling #body안의 여러 p중에 다음 p로 넘어가기

for tag in soup.find_all('p'):
    print(tag.get_text())
body.get_text()

links = soup.find_all('a') #클릭가능한 링크 태그 찾기
for link in links:
    href = link['href'] #href 속성으로 링크 주소만 얻기
    text = link.string
    print(text + ': ' + href)

#import url open lib
from urllib.request import urlopen
import ssl
context = ssl._create_unverified_context() #certificate verify error
url = 'https://finance.naver.com/marketindex/'
page = urlopen(url, context=context)
soup = BeautifulSoup(page, 'html.parser')
print(soup.find_all('span', 'value')[0].string)

 

df 만들기

 

from bs4 import BeautifulSoup
from urllib.request import urlopen
import ssl #context for http
import re
import urllib.parse #url join
context = ssl._create_unverified_context()
url = "https://www.chicagomag.com/Chicago-Magazine/November-2012/Best-Sandwiches-Chicago/"
url_base = "https://www.chicagomag.com"
html = urlopen(url, context=context)
soup = BeautifulSoup(html, 'html.parser')
#export information
rank=[]
main_menu=[]
cafe_name=[]
url_add=[]
list_soup=soup.find_all('div', 'sammy') #html에서 div태그의 sammy 클래스 모두 찾기
for item in list_soup:
    rank.append(item.find(class_="sammyRank").get_text())
    tmp_string=item.find(class_="sammyListing").get_text()
    main_menu.append(re.split(("\n|\r\n"), tmp_string)[0])
    cafe_name.append(re.split(("\n|\r\n"), tmp_string)[1])
    url_add.append(urllib.parse.urljoin(url_base, item.find('a')['href']))
#convert to df
import pandas as pd
data={"Rank":rank,"Menu":main_menu,"Cafe":cafe_name,"URL":url_add}
df=pd.DataFrame(data, columns=["Rank","Menu","Cafe","URL"])
df.to_csv('./data/chicago_df.csv', sep=',', encoding='utf-8')

 

html에서 필요한 값만 저장하기

 

from bs4 import BeautifulSoup
from urllib.request import urlopen
from tqdm import tqdm #progress bar

import pandas as pd
df=pd.read_csv('./data/chicago_df.csv', index_col=0)

import ssl
context = ssl._create_unverified_context()

price=[]
address=[]
for n in tqdm(df.index):
    html=urlopen(df['URL'][n], context=context)
    soup_tmp=BeautifulSoup(html, 'lxml')
    gettings=soup_tmp.find('p', 'addy').get_text()
    price.append(gettings.split()[0][:-1])
    address.append(' '.join(gettings.split()[1:-2]))
df['Price']=price
df['Address']=address
df=df.loc[:, ['Rank','Cafe','Menu','Price','Address']]
df.set_index('Rank',inplace=True)
df.to_csv('./data/chicago_df_price_address.csv',sep=',',encoding='UTF-8')

 

map으로 만들기

 

import pandas as pd
import numpy as np
from tqdm import tqdm
#get csv file
df=pd.read_csv('./data/chicago_df_price_address.csv', index_col=0)
#get address
import googlemaps
gmaps_key = " "
gmaps = googlemaps.Client(key=gmaps_key)
lat=[]
lng=[]
for n in tqdm(df.index):
    if df['Address'][n] != 'Multiple':
        target_name = df['Address'][n]+', '+'Chicago'
        gmaps_output = gmaps.geocode(target_name)
        location_output = gmaps_output[0].get('geometry')
        lat.append(location_output['location']['lat'])
        lng.append(location_output['location']['lng'])
    else:
        lat.append(np.nan)
        lng.append(np.nan)
df['lat']=lat
df['lng']=lng
#mark information
import folium
mapping = folium.Map(location=[df['lat'].mean(), df['lng'].mean()], zoom_start=11)
for n in df.index:
    if df['Address'][n] != 'Multiple':
        folium.Marker([df['lat'][n], df['lng'][n]], popup=df['Cafe'][n]).add_to(mapping)
mapping.save('./data/map_ch.html')

 

'데이터 사이언스 공부 > 파이썬으로데이터주무르기' 카테고리의 다른 글

time series  (0) 2020.05.12
self gas station analysis  (0) 2020.05.12
crime analysis  (0) 2020.05.12
cctv analysis  (0) 2020.05.12