본문 바로가기
코딩 연습/파이썬 크롤링

파이썬 크롤링 기초 예제

by good4me 2022. 6. 16.

goodthings4me.tistory.com

[네이버 지식인 질문 건 답변] 구글 메인 페이지의 구글 로그 이미지 추출하는 방법, 임의의 html 코드에서 <img>태그의 속성값 추출하여 리스트로 만드는 방법

 

 

파이썬 크롤링 연습하기

 

[구글 로고 이미지 url 추출]

import requests
from bs4 import BeautifulSoup
import urllib.parse

header = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'
}
url = 'https://www.google.com/'
resp = requests.get(url, headers=header)
soup = BeautifulSoup(resp.text, 'html.parser')

google_image = soup.find('img', class_='lnXdpd')
print(urllib.parse.urljoin(url, google_image['src']))



[실행 결과]
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png
  • 구글은 헤더의 usrt-agent를 주어야 크롤링이 됨
  • urllib 모듈 parse.urljoin으로 이미지 URL 완성시킴

 

good4me.co.kr

 

[임의의 html 코드에서 이미지 src 값 추출]

from bs4 import BeautifulSoup

html = '''
<div class="cont">
    <div style="text-align: center;"><img alt="" ec-data-src="호랑이.jpg" style="font-size: 9pt;"></div>
    <div style="text-align: center;"><img alt="" ec-data-src="개구리.jpg" style="font-size: 9pt;"></div>
    <div style="text-align: center;"><img alt="" ec-data-src="오징어.jpg" style="font-size: 9pt;"></div>
    <div style="text-align: center;"><img alt="" ec-data-src="얼룩말.jpg" style="font-size: 9pt;"></div>
    <div style="text-align: center;"><img alt="" ec-data-src="라이언.jpg" style="font-size: 9pt;"></div>
    <div style="text-align: center;"><img alt="" ec-data-src="오렌지.jpg" style="font-size: 9pt;"></div>
</div>
'''

soup = BeautifulSoup(html, 'html.parser')
animal_list = [animal['ec-data-src'] for animal in soup.select('div.cont img')]
print(animal_list)



[실행 결과]
['호랑이.jpg', '개구리.jpg', '오징어.jpg', '얼룩말.jpg', '라이언.jpg', '오렌지.jpg']

 

 

 

 

 

댓글