BeautifulSoup : html 코드를 Python이 이해하는 객체 구조로 변환하는 Parsing을 맡고 있고, 이 라이브러리를 이용해 우리는 제대로 된 '의미있는' 정보를 추출해 낼 수 있다.
먼저 터미널창에 pip install BeautifulSoup 라이브러리 설치
from bs4 import BeautifulSoup #라이브러리를 불러엄
from urllib.request import urlopen #
response = urlopen('https://en.wikipedia.org/wiki/Main_Page') #url을 불러옴
soup = BeautifulSoup(response, 'html.parser') #url에서 html.parser분석
for anchor in soup.find_all('a'): #a태그를 찾아서
print(anchor.get('href', '/')) #a태그가 있는 주소를 print
3. 연예인 사진 크롤링
import os
import re
import requests
from bs4 import BeautifulSoup
def getImage(keyword,no):
url="https://search.naver.com/search.naver?where=image&sm=tab_jum&query="+keyword
html = requests.get(url)
bs_html = BeautifulSoup(html.content,"html.parser")
photowall = bs_html.find('div',{"class":"photowall"})
img_list = photowall.find_all("img",{"class":"_img"})
# for i in range(len(img_list)):
for i in range(no):
if not os.path.exists(keyword):
os.makedirs(keyword)
img_link = re.findall('data-source="(.+?)"',str(img_list[i]))[0]
img_con = requests.get(img_link).content
file = open("%s/" %keyword +keyword+str(i+1)+".jpg","wb")
file.write(img_con)
file.close()
print(img_link)
getImage('아이린',50) #아이린사진 50장 크롤링