TIL 191125 & before (1)

김상훈·2019년 11월 26일
0

데이터 크롤링하기

Selenium 사용.
PhantomJS는 Python 2에서나 쓸 수 있다고 한다.
참고로, Python 2는 더이상 업데이트 되지 않는다.
그러므로 3을 쓰는게 낫지.
그래서 PhantomJS 대신 Chrome Driver을 사용하였다.

DCInside 댓글 크롤링 성공.
비교적 쉬운 편이었다.

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('disable-gpu')

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

f1 = open('/home/shkim/Desktop/cuss_dat/train/cussdata.txt', 'a')
f2 = open('/home/shkim/Desktop/cuss_dat/train/cusslabel.txt', 'a')

# dcinside
for idx in range(5360005, 5360100): # 글번호
  driver.get('주소를 입력하세요' + str(idx))
  children = driver.find_elements_by_xpath('//*[@class="usertxt ub-word"]')
  print("article number: " + str(idx))
  if len(children) > 0:
    for child in children:
      comment = " ".join(child.text.split())
      print(comment)
      yes_no = input('욕이면 1, 아니면 0: ')
      if (yes_no == ""):
        continue
      while (yes_no != "0") and (yes_no != "1"):
        yes_no = input('다시 입력해주세요: ')
      f1.write(comment + '\n')
      f2.write(yes_no + '\n')

driver.quit()
f1.close()
f2.close()

네이버 댓글 크롤링 성공.
비교적 어려운 편이었다.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()

options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument('disable-gpu')

driver = webdriver.Chrome('../cuss_learn/chromedriver', chrome_options=options)

# 네이버 뉴스
driver.get('https://entertain.naver.com/ranking/comment/list?oid=076&aid=0003499040')

click_freq = 5

WebDriverWait(driver, 10).until(
  EC.visibility_of_element_located((By.XPATH, '//*[@id="cbox_module"]/div/div[6]/div[1]/div/ul/li[3]/a/span[2]'))
).click()

for i in range(0, click_freq):
  WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//*[@class="u_cbox_btn_more"]'))
  ).click()

elements = WebDriverWait(driver, 10).until(
  EC.presence_of_all_elements_located((By.XPATH, '//*[@class="u_cbox_contents"]'))
)

f1 = open('/home/shkim/Desktop/cuss_dat/train/cussdata.txt', 'a')
f2 = open('/home/shkim/Desktop/cuss_dat/train/cusslabel.txt', 'a')

for element in elements:
  comment = element.text
  if len(comment) > 0:
    print(comment)
    yes_no = input('비난, 평가면 1, 아니면 0: ')
    while (yes_no != "0") and (yes_no != "1"):
      yes_no = input('다시 입력해주세요: ')
    f1.write(comment + '\n')
    f2.write(yes_no + '\n')

driver.quit()  

네이버 댓글의 경우
댓글이 비동기적으로 불려왔기 때문에
BeautifulSoap으로는 크롤링이 어려웠다.

게다가 더보기를 클릭하지 않으면 댓글이
20개밖에 불려오지 않았기 때문에
더보기를 누르는 것을 크롬 드라이버로 구현해야 했다.

지금도 "더보기 버튼이 화면 상에 없다"라는
에러가 걸리긴 하지만 다시 실행해보면
정상적으로 실행된다.
아마 인터넷 속도와 연관되어있는 듯 하다.

추가적으로,
욕인지 아닌지 구분하는 기준이 모호했다.
그리고 비꼬는 것도 많았는데,
모델에 어떤 데이터를 줘야 하는지 고민이 많았다.

profile
남과 비교하지 말자.

0개의 댓글