Visual Studio Code를 이용하였습니다.
1. 웹 크롤링
웹 사이트에 있는 정보를 수집하고자 할 때, 수집하고자 하는 양이 많지 않다면 직접 수동으로 수집할 수 있습니다. 하지만, 수집하고자 하는 양이 방대하고 시간이 오래 걸리는 작업이라면 웹 크롤링을 통해 빠르게 원하는 정보만 수집하여 저장할 수 있습니다.
2. Selenium 설치
Terminal에서 아래와 같이 pip를 사용하여 Selenium와 BeautifulSoup을 설치합니다.
selenium은 3버전으로 작성되었습니다.
최신 selenium은 4버전으로 아래 코드와 맞지 않을 수 있습니다.
아래 코드를 사용할 경우 pip install selenium==3 으로 설치해주세요.
pip install Selenium
pip install BeautifulSoup
pip requests
3. 브라우저 별 드라이버 설치
해당 링크에서 사용할 브라우저 드라이버를 설치합니다.
Chrome: https://sites.google.com/chromium.org/driver/
ChromeDriver - WebDriver for Chrome
WebDriver is an open source tool for automated testing of webapps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. ChromeDriver is a standalone server that implements the W3C WebDriver
sites.google.com
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver
WebDriver - Microsoft Edge Developer
Microsoft Edge Legacy Microsoft WebDriver for Microsoft Edge Legacy versions 18 and 19 is a Windows Feature on Demand which ensures that it’s always up to date automatically and enables some new ways to get Microsoft WebDriver. To get started you will ha
developer.microsoft.com
Firefox: https://github.com/mozilla/geckodriver/releases
Releases · mozilla/geckodriver
WebDriver for Firefox. Contribute to mozilla/geckodriver development by creating an account on GitHub.
github.com
설치 후, 다운로드 받은 드라이버를 원하는 경로에 이동시켜 줍니다.
※ 본인이 사용하는 브라우저 버전과, 다운로드한 드라이버 버전이 동일해야 합니다!
4. 웹 크롤링
4-1. requests 이용
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import requests
import sys
url = 'https://naver.com'
response = requests.get(url)
href_list = [] # 크롤링 URL
if response.status_code == 200:
# HTML 코드를 가져온다
html = response.text
soup = BeautifulSoup(html, 'html.parser')
# a태그를 모두 찾음
a = soup.find_all('a') # 리스트
# class가 col인 div 태그를 찾음
a_class = soup.find("div", {"class":"col"})
href = a_class.get("href")
for i in a:
try:
href = i.attrs['href'] # href를 찾음
text = i.string
except:
pass
href_list.append(href)
# 주소만 반환한다.
for name in href_list[:]:
if name.find('?idx=') == -1:
href_list.remove(name)
4-2. selenium 사용
from selenium import webdriver #사용하는 모듈 호출
from bs4 import BeautifulSoup
import sys #나중에 print 출력을 txt파일로 저장하기 위하여 사용됩니다.
import time #밑에 time.sleep(1)에서 사용됩니다.
import requests
sys.stdout=open("output.txt", "a") #나중에 output.txt라는 파일로 저장하는데, a: 이어 쓰기, w: 덮어쓰기, 경로지정 가능합니다.
path="C:/Users/owner/Desktop/chromedriver.exe" #브라우저 드라이버가 위치한 경로를 입력합니다.
driver=webdriver.Chrome(path)
driver.implicitly_wait(3) #3초
url="https://www.naver.com" #웹 크롤링 하고자 하는 홈페이지 주소를 적습니다.
time.sleep(1) #1초동안 지연됩니다. 컴퓨터 성능에 따라 지연이 필요하다면 사용합니다. (import time)
driver.get(url) #웹 크롤링할 사이트를 호출합니다.
#driver.find_element_by_name("HTML NAME")
#driver.find_element_by_xpath("//*[@id~~]")
#driver.find_element_by_tag_name(H1) #필요한 element를 찾아 위치를 지정해줍니다.
## selenium==4
##from selenium.webdriver.common.by import By
##driver.find_element(By.XPATH, "//*[@id="account"]/a").click()
driver.find_element_by_xpath('//*[@id="account"]/a').click() #네이버 홈페이지의 [NAVER 로그인]을 클릭한다
driver.find_element_by_xpath('//*[@id="account"]/a').send_keys('아이디') # 아이디 텍스트를 쓴다
def iframe_move():
"""iframe 진입합니다."""
content = driver.find_element_by_tag_name("iframe")
driver.switch_to.frame(content)
def iframe_out():
"""iframe 탈출합니다."""
driver.switch_to.default_content()
# 창 전환
print(driver.window_handles)
driver.switch_to.window(driver.window_handles[1])
########################참고########################
########################참고########################
html=driver.page_source #element 가져오기
soup=BeautifulSoup(html, "html.parser")
datas=soup.select(".word") #class가 ***.word 인 텍스트를 모두 선택합니다.
#datas=soup.find_all('div',{'class':'nick'}) # class가 nick인 데이터 찾는다.
for i in datas:
print(i.get_text()) #텍스트만 출력합니다.
for data in datas:
print(data.text.strip()) #strip은 양쪽 공백을 지울 수 있으며 특정 문자도 삭제 가능합니다.
driver.quit() #브라우저를 종료합니다.
HTML은 홈페이지마다 상이하고
모든 경우를 다 설명할 수 없기 때문에
코드를 참고하여 사용할 전략을 직접 만들어 원하는 데이터를 가공할 수 있습니다.
'컴퓨터 > Python' 카테고리의 다른 글
[Python] 파이썬, 투자할 주식 종목 자동으로 추려보자! (0) | 2021.11.22 |
---|---|
[Python] 파이썬, HTML로 카카오맵 api 해상도 높은 큰 지도 만들기 (0) | 2021.11.18 |
[Python] 파이썬, 로컬 서버 localhost 간단하게 만들기(터미널, 코드) (0) | 2021.11.13 |
딥페이크, 얼굴 바꾸기: Faceswap 설치 및 사용법 (2) (62) | 2020.11.12 |
딥페이크, 얼굴 바꾸기: Faceswap 설치 및 사용법 (1) (4) | 2020.11.12 |