Today's

길을 나서지 않으면 그 길에서 만날 수 있는 사람을 만날 수 없다

파이썬 스크립트

파이썬 으로 따라하는 자동화 스크립트 자동 댓글 달기...

Billcorea 2021. 12. 12. 09:55
반응형

매일 처럼 쏟아지는 feed 에 댓글을 달아보자 (노노~ 찾아 오는 이가 없는 나의 블로그에 방문객 유인을 위한 방책으로) 자동 댓글 달기를 해 보기로 했다.

# coding=utf-8

import ssl
import sqlite3
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import os.path
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
from selenium.webdriver.remote.webelement import WebElement
from datetime import datetime
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.keys import Keys

conn = sqlite3.connect("test.sqlite", isolation_level=None)
rs = conn.cursor()
# 한번 갔던 글을 더 작성을 하지 않도록 하기 위해서 저장하기
rs.execute("CREATE TABLE IF NOT EXISTS urlInfo \
        (id integer PRIMARY KEY, urlName text, writeDate text)")

path = "C:\\Users\\nari4\\AppData\\Local\\Programs\Python\\Python37\\chromedriver.exe"
driver = webdriver.Chrome(path)

driver.implicitly_wait(2)
# 티스토리 접속
driver.get('https://www.tistory.com/')
# 계정 로그인 버튼 클릭
driver.find_element_by_xpath('//*[@id="kakaoHead"]/div/div[3]/div/a').click()
driver.find_element_by_xpath('//*[@id="cMain"]/div/div/div/a[1]/span[2]').click()
time.sleep(1)
# 로그인
username=driver.find_element_by_xpath('//*[@id="id_email_2"]')
username.send_keys('카카오ID')
password=driver.find_element_by_xpath('//*[@id="id_password_3"]')
password.send_keys('비밀번호')
time.sleep(1)
driver.find_element_by_xpath('//*[@id="login-form"]/fieldset/div[8]/button[1]').click()
time.sleep(1)
# 로그인이 되면 feed 로 이동
driver.get("https://www.tistory.com/feed")
time.sleep(1)
html = driver.find_element_by_class_name("list_tistory").get_attribute("innerHTML")

# 내가 읽어야 하는 feed 목록을 추려본다.
# 다만, 아직은 전체가 다 나오지는 않는다. 이유는 좀 더 찾아 보는 것으로 해야겠다.
soup = BeautifulSoup(html.encode("utf-8"),'html.parser')
urls=soup.find_all(class_="inner_desc_tit")
for url in urls:
    urlPath = url['href']
    urlStr = urlPath.split('//')[1]
    print(urlStr)
    #이미 다녀간 곳인지 확인 
    rs.execute(''' select count(*) from urlInfo 
                    where urlName = "{0}" '''.format(urlStr))
    # 이미 다녀간 곳이면 패스                
    if (rs.fetchone()[0] == 1):
        print(urlPath + ' 이미 작성한 경로 입니다.')
    else:
        # 그렇지 않다면 작성하기
        print(urlPath + ' 작성중... ')
        nId = urlStr.split('/')[1]
        driver.get(urlPath)
        driver.implicitly_wait(30)
        comments = driver.find_element_by_name("comment")
        comments.send_keys("포스팅 잘 읽고 갑니다.  좋은글 감사합니다.  제 블로그에도 방문 부탁 드립니다.")
        print(nId)
        # 버튼을 클릭하고 싶지만, 버튼이 한가지가 아닌 것 같아서 스크립트 실행으로 대신함.
        # 21.09.01 스크립트 실행은 안되는 경우가 발생 됨 다시 버튼 클릭으로 수정
        #driver.execute_script('addComment(this, {0}); return false;'.format(nId))
        commentsBtn = driver.find_element_by_class_name("btn")
        commentsBtn.click();
        rs.execute(''' insert into urlInfo (urlName,  writeDate) 
                       values ("{0}", "{1}") '''.format(urlStr,
                                                                                              datetime.today().strftime(
                                                                                                  "%Y%m%d%H%M%S")))
    print("next .....")

rs.close()
print("Job END ... ")
driver.close()

실행한 결과는 아래 그림 처럼 feed 작성글에 자동으로 댓글을 작성해 준다.

 

 

 

관리자님들께서 불평을 하지 않으신다면 ... 이렇게 댓글 쓰기를 마무리 해 본다.

 

ps. 2021.09.01 스크립트 실행중 오류가 있는 것 같아서 수정함.  수정한 부분은 아래 내용임.

        # 21.09.01 스크립트 실행은 안되는 경우가 발생 됨 다시 버튼 클릭으로 수정
        #driver.execute_script('addComment(this, {0}); return false;'.format(nId))
        try:
            commentsBtn = driver.find_element_by_class_name("btn")
            commentsBtn.click();
        except:
            try:
                commentsBtn = driver.find_element_by_class_name("btn_enter")
                commentsBtn.click();
            except:
                commentsBtn = driver.find_element_by_class_name("btn_register")
                commentsBtn.click();

그런데 실제 적용해서 운영을 하다보니... 버튼 class 가 btn , btn_enter, btn_register 등등 여러개가 발견 되었다.

그래서 일단은 다시 수정했다.

반응형