Python

[파이썬] 네이버 인기검색 키워드 20위 랜덤으로 1개 고르기

Playdev 2023. 7. 17. 22:45
728x90

네이버 데이터랩에서 인기검색 키워드를 가져와 랜덤하게 한 가지 출력하는 코드이다.

최근 관심사 트렌드를 알기 위해 필요했어서 진행했던 코드를 기록해본다.

 

# 패키지 호출
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import chromedriver_autoinstaller
import urllib.request
import warnings
import shutil
import subprocess
import time
import requests
import random

# 1부터 20까지 중에 랜덤추출
ranking = random.randrange(1,20)

warnings.filterwarnings('ignore')

options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')

driver = webdriver.Chrome(chrome_options=options, executable_path='/usr/bin/chromedriver')

#최대창 필요없음
driver.maximize_window()
time.sleep(3)
driver.implicitly_wait(10)

action = ActionChains(driver)

#네이버데이터랩 url호출
driver.get(url='https://datalab.naver.com/shoppingInsight/sCategory.naver')

time.sleep(1)

# 기기클릭
driver.find_element_by_xpath('//*[@id="18_device_0"]').click()

# 분야클릭
driver.find_element_by_xpath('//*[@id="content"]/div[2]/div/div[1]/div/div/div[1]/div/div[1]/span').click()

# 디지털/가전 클릭
driver.find_element_by_xpath('//*[@id="content"]/div[2]/div/div[1]/div/div/div[1]/div/div[1]/ul/li[4]/a').click()

# 조회 클릭
driver.find_element_by_xpath('//*[@id="content"]/div[2]/div/div[1]/div/a').click()

# 상위20개 키워드 담을 배열변수
keyword2=[]

# 상위1위부터 20위까지 추출 및 배열변수에 저장
for j in range(1, 21):
        path = f'//*[@id="content"]/div[2]/div/div[2]/div[2]/div/div/div[1]/ul/li[{j}]/a'
        result = driver.find_element_by_xpath(path).text
        keyword = result.split('\n')
        keyword2.append(keyword[1])
        time.sleep(0.1)
driver.close()
driver.quit()

# 랜덤으로 선택한 키워드 출력
print(keyword2[ranking])

 

 

 
728x90