본문 바로가기

카테고리 없음

2024.05.21 -- 크롤링 2일차(셀레니움)

1.셀레니움

  • 셀레니움은 브라우저를 컨트롤 할 수 있도록 지원하는 라이브러리
!pip install selenium
!pip install chromedriver_autoinstaller

필요한 라이브러리를 깔아준다.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()

크롬으로 새로운 웹사이트가 하나 열린다.

 

driver.get('https://www.google.com')

구글로 웹사이트를 바꿔주고

search = driver.find_element('name','q')
search.send_keys('기분')

검색창에 '기분'이 작성된다.

 

search.send_keys(Keys.RETURN)

그대로 기분 이란 단어를 검색한다.

# 정리
driver = webdriver.Chrome()
driver.get('https://www.google.com')
search = driver.find_element('name','q')
search.send_keys('미세먼지')
search.send_keys(Keys.RETURN)

위의 과정을 한번에 연결해서 실행하면 다음과 같이 나온다.

 

이번엔 네이버 웹툰에서 베스트 댓글과 전체 댓글을 크롤링 해오는 코드를 짜보겠다.

driver = webdriver.Chrome()
driver.get('https://comic.naver.com/webtoon/detail?titleId=783053&no=134&week=tue')

네이버웹툰 김부장이라는 곳으로 이동한다.

!pip install bs4

필요한 라이브러리 install해준다

from bs4 import BeautifulSoup
soup = BeautifulSoup(driver.page_source)
comment_area = soup.findAll('span',{'class':'u_cbox_contents'})
print(comment_area)
[<span class="u_cbox_contents" data-lang="ko" style="">다음주 월 입대라 다음화 못보겠네...나라를 위해 훈련소간다</span>, <span class="u_cbox_contents" data-lang="ko" style="">보이지 얘들아, 그러니까 우리나라 군인분들 보면항상 존경심 가져라 주한미군이랑 대우가 너무 다르다</span>, <span class="u_cbox_contents" data-lang="ko" style="">이나라는 원래부터 국민이 지켜왔다 크으으으으으으으으으으으으으으으으으으으</span>, <span class="u_cbox_contents" data-lang="ko" style="">2024.ver 택티컬 김부장은 대체 어떻길래 ㅋㅋ</span>, <span class="u_cbox_contents" data-lang="ko" style="">대식이 그냥 한국판 걸어다니는 자비스 아니냐 ㅋㅋㅋ</span>, <span class="u_cbox_contents" data-lang="ko" style="">특기는 보급인데, 피지컬은 국보급이네ㅋㅋㅋㅋㅋ</span>, <span class="u_cbox_contents" data-lang="ko" style="">수달 하나 진짜 존나 낭만 철철 넘친다.... 저게 진짜 애국자고 군인이지... 캬 몇 번을 돌려봐도 소름돋는다</span>, <span class="u_cbox_contents" data-lang="ko" style="">대식이 생긴게 촉법소년 핑크머리여자분이랑 먼가닮은거같기도하고</span>, <span class="u_cbox_contents" data-lang="ko" style="">진짜 멋있는 말이네이 나라는 국민과 군인이 지켜온 나라는 말 ㅎㅎ</span>, <span class="u_cbox_contents" data-lang="ko" style="">나잖아!</span>, <span class="u_cbox_contents" data-lang="ko" style="">아레스 금문조지고 옆동네가서 장과장좀혼내줘...</span>, <span class="u_cbox_contents" data-lang="ko" style="">대식이 바키에 나올만한 인상이네 ㅋㅋㅋㅋ</span>]

베스트 댓글 크롤링

print('******베스트댓글*********')
for i in range(len(comment_area)):
    comment = comment_area[i].text.strip()
    print(comment)
    print('-'*30)

베스트 댓글 출력

******베스트댓글*********
다음주 월 입대라 다음화 못보겠네...나라를 위해 훈련소간다
------------------------------
보이지 얘들아, 그러니까 우리나라 군인분들 보면항상 존경심 가져라 주한미군이랑 대우가 너무 다르다
------------------------------
이나라는 원래부터 국민이 지켜왔다 크으으으으으으으으으으으으으으으으으으으
------------------------------
2024.ver 택티컬 김부장은 대체 어떻길래 ㅋㅋ
------------------------------
대식이 그냥 한국판 걸어다니는 자비스 아니냐 ㅋㅋㅋ
------------------------------
특기는 보급인데, 피지컬은 국보급이네ㅋㅋㅋㅋㅋ
------------------------------
수달 하나 진짜 존나 낭만 철철 넘친다.... 저게 진짜 애국자고 군인이지... 캬 몇 번을 돌려봐도 소름돋는다
------------------------------
대식이 생긴게 촉법소년 핑크머리여자분이랑 먼가닮은거같기도하고
------------------------------
진짜 멋있는 말이네이 나라는 국민과 군인이 지켜온 나라는 말 ㅎㅎ
------------------------------
나잖아!
------------------------------
아레스 금문조지고 옆동네가서 장과장좀혼내줘...
------------------------------
대식이 바키에 나올만한 인상이네 ㅋㅋㅋㅋ
  • Xpath: 기존의 컴퓨터 파일 시스템에서 사용하는 경로 표현식과 유사한 경로 언어
driver.find_element('xpath','/html/body/div[1]/div[5]/div/div/div[5]/div[1]/div[3]/div/div/div[4]/div[1]/div/ul/li[2]/a/span[2]')

xpath 따와서 전체댓글을 크롤링해온다

<selenium.webdriver.remote.webelement.WebElement (session="2c117b34993f4f713ca112ca5d190824", element="f.DE66926D1F539E64C6907D46BDAFA05D.d.0443E4F50ED754AE5CBAD4C3352032D2.e.186")>
soup = BeautifulSoup(driver.page_source)
comment_area = soup.findAll('span',{'class':'u_cbox_contents'})
print(comment_area)
[<span class="u_cbox_contents" data-lang="ko" style="">다음주 월 입대라 다음화 못보겠네...나라를 위해 훈련소간다</span>, <span class="u_cbox_contents" data-lang="ko" style="">보이지 얘들아, 그러니까 우리나라 군인분들 보면항상 존경심 가져라 주한미군이랑 대우가 너무 다르다</span>, <span class="u_cbox_contents" data-lang="ko" style="">이나라는 원래부터 국민이 지켜왔다 크으으으으으으으으으으으으으으으으으으으</span>, <span class="u_cbox_contents" data-lang="ko" style="">2024.ver 택티컬 김부장은 대체 어떻길래 ㅋㅋ</span>, <span class="u_cbox_contents" data-lang="ko" style="">대식이 그냥 한국판 걸어다니는 자비스 아니냐 ㅋㅋㅋ</span>, <span class="u_cbox_contents" data-lang="ko" style="">특기는 보급인데, 피지컬은 국보급이네ㅋㅋㅋㅋㅋ</span>, <span class="u_cbox_contents" data-lang="ko" style="">수달 하나 진짜 존나 낭만 철철 넘친다.... 저게 진짜 애국자고 군인이지... 캬 몇 번을 돌려봐도 소름돋는다</span>, <span class="u_cbox_contents" data-lang="ko" style="">대식이 생긴게 촉법소년 핑크머리여자분이랑 먼가닮은거같기도하고</span>, <span class="u_cbox_contents" data-lang="ko" style="">진짜 멋있는 말이네이 나라는 국민과 군인이 지켜온 나라는 말 ㅎㅎ</span>, <span class="u_cbox_contents" data-lang="ko" style="">나잖아!</span>, <span class="u_cbox_contents" data-lang="ko" style="">아레스 금문조지고 옆동네가서 장과장좀혼내줘...</span>, <span class="u_cbox_contents" data-lang="ko" style="">대식이 바키에 나올만한 인상이네 ㅋㅋㅋㅋ</span>]
print('******전체댓글*********')
for i in range(len(comment_area)):
    comment = comment_area[i].text.strip()
    print(comment)
    print('-'*30)
******전체댓글*********
다음주 월 입대라 다음화 못보겠네...나라를 위해 훈련소간다
------------------------------
보이지 얘들아, 그러니까 우리나라 군인분들 보면항상 존경심 가져라 주한미군이랑 대우가 너무 다르다
------------------------------
이나라는 원래부터 국민이 지켜왔다 크으으으으으으으으으으으으으으으으으으으
------------------------------
2024.ver 택티컬 김부장은 대체 어떻길래 ㅋㅋ
------------------------------
대식이 그냥 한국판 걸어다니는 자비스 아니냐 ㅋㅋㅋ
------------------------------
특기는 보급인데, 피지컬은 국보급이네ㅋㅋㅋㅋㅋ
------------------------------
수달 하나 진짜 존나 낭만 철철 넘친다.... 저게 진짜 애국자고 군인이지... 캬 몇 번을 돌려봐도 소름돋는다
------------------------------
대식이 생긴게 촉법소년 핑크머리여자분이랑 먼가닮은거같기도하고
------------------------------
진짜 멋있는 말이네이 나라는 국민과 군인이 지켜온 나라는 말 ㅎㅎ
------------------------------
나잖아!
------------------------------
아레스 금문조지고 옆동네가서 장과장좀혼내줘...
------------------------------
대식이 바키에 나올만한 인상이네 ㅋㅋㅋㅋ
------------------------------

 

 

인스타그램 크롤링

 

1.로그인

import chromedriver_autoinstaller
from selenium import webdriver
driver = webdriver.Chrome()
url = 'https://www.instagram.com/'
driver.get('https://www.instagram.com/')

id = 'kingju232@gmail.com'
pw = 'discom135!@'
input_id = driver.find_element('xpath','/html/body/div[2]/div/div/div[2]/div/div/div[1]/section/main/article/div[2]/div[1]/div[2]/form/div/div[1]/div/label/input')
input_pw = driver.find_element('xpath','/html/body/div[2]/div/div/div[2]/div/div/div[1]/section/main/article/div[2]/div[1]/div[2]/form/div/div[2]/div/label/input')






input_id.send_keys(id)
input_pw.send_keys(pw)
driver.find_element('xpath','/html/body/div[2]/div/div/div[2]/div/div/div[1]/section/main/article/div[2]/div[1]/div[2]/form/div/div[3]/button').click()

인스타 그램 로그인.

 

2.해시태그 검색

 

hashtag = '맛점'
url = f'http://www.instagram.com/explore/tags/{hashtag}'
driver.get(url)

맛점 해시태그 검색

 

3.스크롤 내리기

import time
for _ in range(2):
    driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')

4.원하는 사진 클릭하기

xpath='/html/body/div[2]/div/div/div[2]/div/div/div[1]/div[1]/div[2]/section/main/article/div/div[2]/div/div[2]/div[2]/a'

driver.find_element('xpath',xpath).click()

5.좋아요 클릭 및 댓글달기

like_xpath = '/html/body/div[8]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[2]/div/div/div[2]/section[1]/span[1]/div/div'
driver.find_element('xpath', like_xpath).click()
driver.find_element('xpath', like_xpath).click()
reply_xpath = '/html/body/div[8]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[2]/div/div/div[2]/section[3]/div/form/div/textarea'
driver.find_element('xpath', reply_xpath).click()
driver.find_element('xpath', reply_xpath).send_keys('좋은정보 감사합니다')

6.함수로 리팩토링

#로그인
def login(id,pw):
    input_id = driver.find_element('xpath','/html/body/div[2]/div/div/div[2]/div/div/div[1]/section/main/article/div[2]/div[1]/div[2]/form/div/div[1]/div/label/input')
    input_pw = driver.find_element('xpath','/html/body/div[2]/div/div/div[2]/div/div/div[1]/section/main/article/div[2]/div[1]/div[2]/form/div/div[2]/div/label/input')
    input_id.send_keys(id)
    input_pw.send_keys(pw)
    driver.find_element('xpath','/html/body/div[2]/div/div/div[2]/div/div/div[1]/section/main/article/div[2]/div[1]/div[2]/form/div/div[3]/button').click()

#해시태그 검색
def search(hashtag):
    url = f'http://www.instagram.com/explore/tags/{hashtag}'
    driver.get(url)

# 좋아요 및 댓글달기
def like_and_comment(comment):
    like_xpath = '/html/body/div[8]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[2]/div/div/div[2]/section[1]/span[1]/div/div'
    driver.find_element('xpath', like_xpath).click()
    
    reply_xpath = '/html/body/div[8]/div[1]/div/div[3]/div/div/div/div/div[2]/div/article/div/div[2]/div/div/div[2]/section[3]/div/form/div/textarea'
    driver.find_element('xpath', reply_xpath).click()
    driver.find_element('xpath', reply_xpath).send_keys('좋은정보 감사합니다')
driver = webdriver.Chrome()
url = 'https://www.instagram.com/'
driver.get('https://www.instagram.com/')
driver.implicitly_wait(3)

id = 'kingju232@gmail.com'
pw = 'discom135!@'

login(id,pw)
time.sleep(4)

hashtag = '사과'
search(hashtag)
time.sleep(4)

like_and_comment('안녕하세요 잘보고갑니다')

 

픽사베이 이미지

 

import chromedriver_autoinstaller
import time
from selenium import webdriver
from urllib.request import Request, urlopen
driver = webdriver.Chrome()
url = 'https://pixabay.com/ko/'
driver.get(url)
search = '리트리버'
url = f'https://pixabay.com/ko/images/search/{search}/'
driver.get(url)
for _ in range(2):
    driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
    time.sleep(2)
xpath='/html/body/div[1]/div[1]/div/div[2]/div[3]/div/div/div[2]/div[6]/div'

driver.find_element('xpath',xpath).click()
image_xpath= '/html/body/div[1]/div[1]/div/div[2]/div[3]/div/div/div[4]/div[3]/div/a/img'
image_url = driver.find_element('xpath',image_xpath).get_attribute('src')
print('image_url: ',image_url)
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
image_byte = Request(image_url, headers={'User-Agent': user_agent})

# 이미지 다운로드 및 저장
with urlopen(image_byte) as response, open('dog.jpg', 'wb') as out_file:
    out_file.write(response.read())
 
print("이미지가 dog.jpg로 저장되었습니다.")

리트리버의 이미지가 주피터 노트북 설정된 경로로 저장된다.

 

def crawl_and_save_image(keyword, pages):
    image_urls = []
    for i in range(1, pages + 1):
        url = f'https://pixabay.com/ko/images/search/{keyword}/?pagi={i}'
        driver.get(url)
        time.sleep(2)
        for _ in range(20):
            driver.execute_script("window.scrollBy(0, window.innerHeight);")
            time.sleep(1)
        image_area_xpath = 'html/body/div[1]/div[1]/div/div[2]/div[3]'
        image_area = driver.find_element(By.XPATH, image_area_xpath)
        image_elements = image_area.find_elements(By.TAG_NAME, 'img')
        for image_element in image_elements:
            image_url = image_element.get_attribute('src')
            print(image_url)
            image_urls.append(image_url)
    if not os.path.exists(keyword):
        os.mkdir(keyword)
    for i in range(len(image_urls)):
        image_url = image_urls[i]
        url = parse.urlparse(image_url)
        filename = image_url.split('/')[-1]
        image_byte = Request(image_url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64;)'})
        f = open(f'{keyword}/{filename}','wb')
        f.write(urlopen(image_byte).read())
        f.close()
driver = webdriver.Chrome()
crawl_and_save_image('호랑이',2)

호랑이 사진이 다운받아지고 저장된다.