데이터 크롤링이란 인터넷 상의 다양한 웹 페이지나 소스코드를 자동으로 탐색하고 정보를 수집하는 프로세스를 말한다.
HTML(Hyper-Text Markup Language)은 웹사이트를 만들때 사용되는 마크업 언어이다.
<a href=“https://www.naver.com”>네이버로 이동</a>
a : 태그 명
href : 속성 (태그의 종류에 따라 사용할 수 있는 속성이 다르다)
import requests
from bs4 import BeautifulSoup
CSS(Cascading Style Sheets) 선택자는 HTML 요소를 스타일링하거나 특정 요소를 선택할 때 사용한다.
클래스 선택자는 ‘class’ 속성을 기반으로 요소를 선택한다.
‘.클래스명’
아이디 선택자 ‘id’ 속성을 기반으로 요소를 선택한다.
‘#아이디명’
response = requests.get('https://m.search.naver.com/search.naver?where=m_news&sm=mtb_jum&query=%EC%BA%A0%ED%95%91')
html=response.text
#print(html)
soup = BeautifulSoup(html, 'html.parser')
news = soup.select('.news_tit')
#print(news)
for i in news:
title = i.text
link = i['href']
print(title, link)
import requests
from bs4 import BeautifulSoup
# 검색어 입력
search = input("검색어를 입력하세요: ")
for page in range(1, 4):
#입력할 검색어를 넣어서 url 저장
url = f"https://m.search.naver.com/search.naver?where=m_news&sm=mtb_jum&query={search}&start={page * 10}"
#requests를 통해 url에 전송하기 -> reponse 저장
response = requests.get(url)
#html에 response로 나온 정보를 test화하여 불러오기
html = response.text
#BeautifulSoup 객체 생성 = HTML 문서를 파싱하고 탐색할 수 있는 도구를 제공
soup = BeautifulSoup(html, 'html.parser')
# CSS 선택자를 이용해 원하는 요소를 선택
news = soup.select('.news_tit')
print(f"------------------------")
for i in news:
title = i.text
link = i['href']
print(title, link)
G마켓(https://www.gmarket.co.kr/)에서 사용자가 검색한 상품
의 정보를 엑셀 파일로 저장한다.
!pip install openpyxl
import openpyxl
import requests
from bs4 import BeautifulSoup
wb = openpyxl.Workbook()
ws = wb.create_sheet('posco')
ws['A1'] = '상품명'
ws['B1'] = '가격'
ws['C1'] = '링크'
# 검색어 입력
search = input("검색어를 입력하세요: ")
#입력할 검색어를 넣어서 url 저장
url = f"https://browse.gmarket.co.kr/search?keyword={search}"
#requests를 통해 url에 전송하기 -> reponse 저장
response = requests.get(url)
#html에 response로 나온 정보를 test화하여 불러오기
html = response.text
#BeautifulSoup 객체 생성 = HTML 문서를 파싱하고 탐색할 수 있는 도구를 제공
soup = BeautifulSoup(html, 'html.parser')
# print(soup)
# CSS 선택자를 이용해 원하는 요소를 선택
flower = soup.select('.box__information-major')
for i in flower:
title = i.select_one('.box__item-title')
title_b = title.select_one('.text__item')['title']
price = i.select_one('.box__item-price')
price_b = price.select_one('.box__price-seller')
price_c = price_b.select_one('.text__value').text
link = title.select_one('.link__item')['href']
print(title_b,price_c,link)
ws.append([title_b,price_c,link])
wb.save(r'C:\Users\gram\anaconda3\Untitled Folder\crawlingtest.xlsx')