어떤 태그는 크롤링이 되고, 어떤 건 seletor이고 어떤 건 그냥 copy고,,
정리를 해보려고 한다.
크롤링해서 데이터를 뽑았으면 csv파일로 생성해야 DB에 넣을 수 있다.
import csv
csv_open = open("product.csv", 'w+', encoding='utf-8', newline='')
# product파일을 csv파일로 쓰기 모드로 만들고 열어줘
csv_writer = csv.writer(csv_open)
tag_writer.writerow(('title', 'description'))
# title과 description 열을 각각 만들어줘
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
import requests
import re #정규표현식을 위해 import
# 데이터를 뽑고자 하는 url
crawling_url = "https://www.billboard.com/charts/hot-100"
# http get request를 통해 url 내에 있는 데이터를 가져오기.
req = requests.get(crawling_url)
# html소스 가져오기
html = req.text
## 첫 인자는 html, 두 번째 인자는 어떤 parser를 이용할지 명시.
## 아래처럼 입력하면 Python 내장 html.parser를 이용한다는 것
> 대부분 이렇게 입력하는 것 같다
soup = BeautifulSoup(html, 'html.parser')
product_list = bs.select('.#container > div.content > div.product_result_wrap.product_result_wrap01 > div > dl > dd:nth-child(2) > div.product_list')
# 개발자도구에서 copy select로 selector 해 올 수 있다
# 이렇게 복사해올 경우 :nth-child(4) 와 같이 하나에 특정하는 코드임을 알 수 있다. 이를 지워주면 그 태그에 속하는 모든 것을 크롤링 해온다
# 앞에 .(온점)을 붙여준다
product_list = bs.select('.product_list')
description = bs.select('.description_list')
# 클래스가 3개라면?
# 클래스가 info이면서 category이면서 hot 인 태그 찾기
food_list = soup.select('.info.category.hot')
# 앞에 #을 붙여준다
food_list = soup.select('#foodContent')
# 문서 전체에서 a 태그 중 속성 값 href를 갖은 태그를 찾기
food_list = soup.select('a[href]')
# id가 bodyContent인 태그의 자손 태그 중에서 a 태그 속성 값 href를 갖은 태그를 찾기
fodd_list = soup.select('#foodContent a[href]')
select는 CSS Selector를 이용해 조건과 일치하는 모든 객체들을 List로 반환해준다.
select의 return 값은 리스트이다. 그래서 요소를 꺼내려면,
1) for 문을 돌린 후,
2) text로 변환해야 한다.
ex .for item in zip(drink_list, url_list): drink = item[0].text url = item[1].text로 요소를 꺼낼 수 있다.
selenium은 동적인 것을 크롤링해야 할 때 써야하는 프레임워크다.
자동으로 클릭하게 하거나, 자동으로 검색어를 입력 후 조회하게 하거나 등 브라우저를 제어할 수 있다.
위코드 과제 중에 스타벅스 크롤링을 하는 게 있었는데, 당연히 정적인 페이지 인 줄 알고, 뷰티풀 숲으로 하루를 다 쏟고나서 자바스크립트인 걸 알고 selenium으로 다시 크롤링한적이 있다 😂
우선 프레임워크를 설치하자
pip install selenium
pip install webdriver-manager
자주 업데이트가 된다고 하니, 새로운 버전으로 업뎃도 자주 하자!
url = "https://www.aesop.com/kr/p/skin/" req = requests.get(url) time.sleep(3) html = req.text
해당 url에 접속 후 로딩이 있을 수 있으니, time.sleep을 준다(3초 기다려줘)
페이지의 단일 element에 접근하는 api,
find_element_by_name('HTML_name')
find_element_by_id('HTML_id')
find_element_by_xpath('/html/body/some/xpath')
find_element_by_css_selector('#css > div.selector')
find_element_by_class_name('some_class_name')
find_element_by_tag_name('h1')
페이지의 여러 요소에 접근하려면
elements이렇게 s 를 붙여준다
참고사이트:
크롤링