[Python 인터넷] 파이썬 셀레늄 네이버 포스트 자동 포스팅 방법

파이썬 셀레늄 네이버 포스트 자동 포스팅 방법

오랜만에 블로그 포스팅을 하게 되어서 기쁘게 생각합니다. 최근에는 GPT 포 등과 같은 기술들에 대한 이야기가 많이 나오고 있는 것 같습니다. 이로 인해 이제는 네이버 블로그나 텍스트 기반의 글쓰기가 크게 변화할 것이라고 생각합니다. 이미 몇몇 부분에서는 변화가 이루어지고 있습니다. 그렇지만 개인적으로는 여전히 이러한 방식으로 그냥 말로 글을 쓰는 것이 더 좋다고 생각합니다. 그래서 앞으로도 이 방식으로 글을 공유할 예정입니다.

 

오늘은 네이버 포스트를 통해 자동 포스팅하는 방법에 대해 약간 소개해드리고자 합니다. 이 방법은 처음 듣는 분들도 많을 것 같습니다. 특히 네이버 블로그를 자동화하여 글을 쓰시는 분들도 있을 것입니다. 네이버 포스트에서도 이와 같은 자동화 방법을 사용할 수 있습니다. 이를 위해 주로 사용되는 방법은 Python의 Selenium 라이브러리를 사용하여 이미지와 텍스트 등을 삽입하는 것입니다.

 

아래는 이 방법을 간략히 설명한 것입니다. 먼저 크롬 드라이버를 구동하여 크롬을 실행합니다. 이 때 디버깅 모드 방식으로 실행합니다. 그리고 네이버 사이트에 로그인하여 포스트 글쓰기를 할 수 있는 페이지로 이동합니다. 이제 글쓰기를 위한 작성 페이지에 들어가서 글을 작성하면 됩니다. 이와 같은 방법을 사용하면 자동화된 글쓰기를 할 수 있습니다.

 

그리고 마지막으로는 이제 글을 쓴 후에 이제 업로드를 하는 부분이 됩니다. 이 부분은 약간 좀 간단하게는 할 수 있겠지만 실제로도 이제 어떤 문제점들이 있을 수도 있고요. 그래서 이런 것들에 대해서는 좀 조금 더 공부를 해서 자신이 하시려는 작업에 맞게끔 약간 수정을 해야 될 수도 있다는 것들이 있을 거예요.

 

이렇게 보면 자동 포스팅이 굉장히 간단하고 쉬운 일처럼 보일 수 있지만 실제로는 그렇게 간단하지 않다는 것을 알 수 있습니다. 여러분들이 이러한 자동 포스팅을 하기 위해서는 프로그래밍 언어에 대한 기본 지식과 함께 웹 개발과 관련된 지식들이 필요합니다. 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

그래도 이러한 자동 포스팅 기능을 응용하면 블로그 포스팅을 조금 더 효율적으로 할 수 있고, 시간을 절약할 수 있기 때문에 도움이 될 것입니다. 이상으로 오늘은 네이버 포스트를 통한 자동 포스팅에 대해서 알아보았습니다. 다음에는 블로그 운영에 있어서 유용한 다른 팁들에 대해서도 알아보겠습니다. 감사합니다.

 

# import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from googleapiclient.http import MediaFileUpload
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import  warnings
from    selenium import webdriver
from    selenium.webdriver.support import expected_conditions as EC
from    selenium.webdriver.common.keys import Keys 
from    selenium.webdriver.common.action_chains import ActionChains
from    selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException
from    bs4      import BeautifulSoup
import  time
import  pyperclip
import  requests
import  datetime
import  pymssql
import  pandas as pd
from  pandas.core.frame import DataFrame
import  matplotlib.pyplot as plt
import  chromedriver_autoinstaller
import  subprocess
from    selenium import webdriver
from    selenium.webdriver.chrome.options import Options
from    selenium.webdriver.common.alert import Alert
import  chromedriver_autoinstaller
import  subprocess
import  shutil 
import  xlrd
import  openpyxl 
import  pygsheets
import  csv
import  re
import  webbrowser
import  os
import  sys
import  urllib.request
import  json
from    pandas.io.json import json_normalize
import  hashlib
import  hmac
import  base64
import  numpy as np
import  autoit #autoit는 반드시 autoit 프로그램이 깔려있어야됨
import  pyautogui
from PIL import ImageGrab
import glob

warnings.filterwarnings('ignore')

#try:
#    shutil.rmtree(r"c:\chrometemp")  #쿠키 / 캐쉬파일 삭제
#except FileNotFoundError:
#    pass

subprocess.Popen(r'C:\Program Files\Google\Chrome\Application\chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\chrometemp"') # 디버거 크롬 구동
option = Options()
option.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
chrome_ver = chromedriver_autoinstaller.get_chrome_version().split('.')[0]
try:
    driver = webdriver.Chrome(f'./{chrome_ver}/chromedriver.exe', options=option)
except:
    chromedriver_autoinstaller.install(True)
    driver = webdriver.Chrome(f'./{chrome_ver}/chromedriver.exe', options=option)
driver.maximize_window() #최대창
time.sleep(3)    
driver.implicitly_wait(10)

action = ActionChains(driver) #액션지정

#네이버 이동

url = 'https://www.naver.com'
driver.get(url)
time.sleep(5)
driver.implicitly_wait(10)

driver.find_element_by_class_name('link_login').click()
time.sleep(1)
driver.implicitly_wait(10)

#id, pw 입력할 곳 찾기

tag_id = driver.find_element_by_name('id')
tag_pw = driver.find_element_by_name('pw')
driver.implicitly_wait(10)

#id 입력

tag_id.click()
pyperclip.copy('id') 
tag_id.send_keys(Keys.CONTROL, 'v')
time.sleep(2)
driver.implicitly_wait(10)

#pw 입력

tag_pw.click()
pyperclip.copy('pw')
tag_pw.send_keys(Keys.CONTROL, 'v')
time.sleep(2)
driver.implicitly_wait(10)

#로그인 버튼 클릭

login_btn = driver.find_element_by_id('log.login')
login_btn.click()
time.sleep(1)
driver.implicitly_wait(10)

#등록안함 클릭

try :
    driver.find_element_by_xpath('//*[@id="new.dontsave"]').click() #등록안함 클릭
except :
    pass
time.sleep(1)
driver.implicitly_wait(10)

#네이버 포스트 주소로 이동

url = 'https://post.naver.com'
driver.get(url)
time.sleep(2)
driver.implicitly_wait(10)

#포스트 쓰기 버튼 클릭

post_btn = driver.find_element_by_xpath('//*[@id="header"]/div[1]/a[3]')
post_btn.click()
time.sleep(3)
driver.implicitly_wait(10)

#팝업 제거

#position = pyautogui.position() # 좌표 객체 얻기 
#print(pyautogui.size()) #화면전체크기 확인하기

#while True :  #마우스 위치 알아내기
#    print( "Current Mouse Position : ", pyautogui.position())
#    time.sleep(1)

# 좌표 위치 입력 (x, y, 버튼, 횟수, 간격)
#pyautogui.click(1368, 370, button='left', clicks=1, interval = 1 ) #팝업창 클릭(완료)
#time.sleep(2)
#driver.implicitly_wait(10)



################# 자동 포스팅

health_naver_posting = pd.read_excel('C:/Users/user/Desktop/folder/folder/blog_viewracle.xlsx')


for i in range(1, 16) :
    url = 'https://post.editor.naver.com/editor'
    driver.get(url) #생략
    time.sleep(1) #생략
    driver.implicitly_wait(10)
    action = ActionChains(driver) #액션지정

    try :  #사이트 떠나기 엔터키 누르기*(사이트 나가기 창이 뜰시 기준)
        # alert 창의 메시지를 확인하고 싶습니다.
        alert = driver.switch_to.alert
        message = alert.text
        print("Alert shows following message: "+ message )
        time.sleep(1)
        # 메시지를 확인했으니 창을 닫습니다.
        alert = driver.switch_to.alert
        alert.accept() #에러 받아들이기
        time.sleep(1)
        driver.implicitly_wait(10)
        driver.get(url)
        time.sleep(1)
        driver.send_keys(Keys.ENTER)  #사이트 떠나기 엔터키 누르기
        driver.implicitly_wait(10)
    except :
        print("no alert")

    try :
        # alert 창의 메시지를 확인하고 싶습니다.
        alert = driver.switch_to.alert
        message = alert.text
        print("Alert shows following message: "+ message )
        time.sleep(2)
        # 메시지를 확인했으니 창을 닫습니다.
        alert = driver.switch_to.alert
        alert.dismiss() #무시하기
        time.sleep(1)
        driver.implicitly_wait(10)
    except :
        print("no alert")

    time.sleep(1) 
    driver.implicitly_wait(10)
    
    
    title_directory = health_naver_posting.loc[i]['title_2']  #제목
    img_file_directory = health_naver_posting.loc[i]['img_directory'] #이미지
    txt_file_directory = health_naver_posting.loc[i]['txt_directory'] #텍스트
    img_dir = img_file_directory #이미지
    
    f = open(txt_file_directory, 'r', encoding='utf-8')  #메모장 파일열기
    f_2 = open(txt_file_directory, 'r', encoding='utf-8')  #메모장 파일열기

    content_list = f.readlines() #본문
    #blogger_title = content_list[0] #제목만
    blogger_title = title_directory #제목만
    blogger_title_2 = blogger_title.replace("\ufeff", "") #제목 필터링
    
    
    
    content_desc = f_2.read() #본문
    tistory_title = str(blogger_title_2) #제목
    
    ############  네이버 포스트 제목 입력
    
    
    
    iframes = driver.find_elements_by_tag_name('iframe')
    driver.switch_to.frame(iframes[0])
    
    #tag = str(tistory_title)  #태그
    tag_title = driver.find_element_by_xpath("//textarea[@placeholder='제목']") #Span 클래스 내 "제목" 단어 찾기
    #tag_title = driver.find_element_by_xpath("//textarea[contains(@placeholder, '제목')]") 
    #tag_title = driver.find_element_by_xpath('//textarea[contains(text(),"제목")]')
    #tag_title = driver.find_element_by_xpath("//textarea[@placeholder='제목' and @class='se_editable se_textarea']")
    
    tag_title.click()  # "제목" 클릭
    time.sleep(1) 
    title = str(tistory_title)
    time.sleep(1) 
    action.send_keys(title).perform()  #입력
    action = ActionChains(driver) #초기화
    time.sleep(1)
    driver.implicitly_wait(10)
    
    #iframes = driver.find_elements_by_tag_name('iframe')
    #print('현재 페이지에 iframe은 %d개가 있습니다.' % len(iframes))
    
    #for i, iframe in enumerate(iframes):
    #    try:
    #        print('%d번째 iframe 입니다.' % i)
    #        # i 번째 iframe으로 변경합니다.
    #        driver.switch_to.frame(iframes[i])
    #        # 변경한 iframe 안의 소스를 확인합니다.
    #        print(driver.page_source)
    #        # 원래 frame으로 돌아옵니다.
    #        driver.switch_to.default_content()
    #    except:
    #        # exception이 발생했다면 원래 frame으로 돌아옵니다.
    #        driver.switch_to.default_content()
    #        # 몇 번째 frame에서 에러가 났었는지 확인합니다.
    #        print('pass by except : iframes[%d]' % i)
    #        # 다음 for문으로 넘어갑니다.
    
    #tag_content = driver.find_element_by_xpath("//div[contains(text(),'내용을')]") #내용 태그
    tag_content = driver.find_element_by_xpath("//div[@class='se_editView']") #내용 태그
    tag_content.click()
    time.sleep(1)
    driver.implicitly_wait(10)
    
    
    
    #### 소개말 넣기
    
    content_1 = "안녕하세요? " +'\n'
    
    action = ActionChains(driver) #초기화
    action.send_keys(content_1).perform() #컨텐츠 입력
    time.sleep(1)
    driver.implicitly_wait(10)
    
    
    
    
    #### 본문 내용 넣기
    
    content_3_detail = str(content_desc) + '\n' + '\n'
    action = ActionChains(driver) #초기화
    action.send_keys(content_3_detail).perform() #컨텐츠 입력
    time.sleep(1)
    driver.implicitly_wait(10)
    
    
    
    #### 이미지 넣기
    driver.switch_to.default_content() # 아이프레임 빠져나오기
    
    file_dir = health_naver_posting.loc[i]['directory'] + '/'
    img_lists = glob.glob(str(file_dir)+'submit_img_*.jpg') #리스트화
    
    
    for n in range(1, len(img_lists)):
        pic_dir = img_lists[n] #해당 이미지 가져오기 (첫번째꺼는 제외)
        pic_dir = pic_dir.replace("\", "/") #디렉토리 수정
        
        tag_picture = driver.find_element_by_xpath('//*[@id="se_side_comp_list"]/li[2]')  #이미지 버튼 주소
        tag_picture.click() #링크 버튼 클릭
        
        time.sleep(2)
        
        handle = "[CLASS:#32770; TITLE:열기]" #Basic Window info 값 handle 변수에 저장
        autoit.win_wait_active("열기", 3)  #이름이 '열기'인 창이 나올 때까지 3초간 대기

        #img_path = "C:/Users/user/Desktop/test/image/test_"+str(keyword)+".jpg" #이미지경로
        img_path = str(pic_dir)   #이미지경로 변경 
        img_path_2 = img_path.replace('/', '\') # 백슬래시는 두번 써야됨

        autoit.control_send(handle, "Edit1", img_path_2) #사진 클릭시 나오는 윈도우 창에서 파일이름(N)에 이미지 경로값 전달
        time.sleep(1)
        autoit.control_click(handle, "Button1") #사진 클릭시 나오는 윈도우 창에서 Button1 클릭
        time.sleep(1)
        
    
    #최종 임시저장 클릭
    
    driver.find_element_by_xpath('//*[@id="se_top_menu_area"]/div[1]/div[3]/ul/li[1]/div[1]').click() #저장 클릭 

driver.close()
driver.quit()

 

 

[출처] https://dataanalytics.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%85%80%EB%A0%88%EB%8A%84-%EB%84%A4%EC%9D%B4%EB%B2%84-%ED%8F%AC%EC%8A%A4%ED%8A%B8-%EC%9E%90%EB%8F%99-%ED%8F%AC%EC%8A%A4%ED%8C%85-%EB%B0%A9%EB%B2%95

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
517 [pyQT] Qt Resource 파일 (.qrc) 적용방법 file 졸리운_곰 2024.05.28 421
516 [Python 인터넷] python 을 사용한 instagram (인스타그램) 자동 포스팅 : Automate Instagram Posts with Python: A Step-by-Step Guide 졸리운_곰 2024.05.19 317
515 [Python 인터넷] python 을 사용한 instagram (인스타그램) 자동 포스팅 : Automating Instagram Posts with Python: A Quick Guide file 졸리운_곰 2024.05.19 374
514 [Python] 클립보드 무엇인가? Pyperclip을 통한 자동화 file 졸리운_곰 2024.05.06 364
» [Python 인터넷] 파이썬 셀레늄 네이버 포스트 자동 포스팅 방법 졸리운_곰 2024.05.05 442
512 [Python] PyQt와 PySide에 대한 잡설 file 졸리운_곰 2024.04.25 253
511 [python 일반] How to Update All Python Packages : 설치된 파이썬 패키지 모두 업데이트 하기 file 졸리운_곰 2024.03.16 604
510 [python 데이터 분석] 국내 경제 100대 통계지표 졸리운_곰 2024.02.18 672
509 [python 데이터 분석] Python 에서 R언어 패키지 호출 : Calling R From Python With rpy2 file 졸리운_곰 2024.01.28 676
508 [pyQT] from PyQt5.QtChart import QLineSeries, QChart, QValueAxis, QDateTimeAxis ImportError: DLL load failed while importing QtChart: 지정된 모듈을 찾을 수 없습니다. 졸리운_곰 2024.01.28 430
507 [pySide] [번역] PySide6 - 시그널, 슬롯 & 이벤트 file 졸리운_곰 2023.12.27 320
506 [pySide] [번역] PySide6로 첫 번째 앱 만들기 ! file 졸리운_곰 2023.12.27 546
505 [python][자료구조] 벡터화 | Vectorization file 졸리운_곰 2023.12.21 330
504 [python][자료구조] Python의 Loop? NO! , Python의 Vectorization? OK!!! file 졸리운_곰 2023.12.21 473
503 [Django] 장고 CORS 크로스 도메인 이슈 졸리운_곰 2023.12.17 504
502 [django] CORS(Cross Origin Resource Sharing) in Django 졸리운_곰 2023.12.17 421
501 [django] Forbidden (CSRF cookie not set.) 오류 해결하기 file 졸리운_곰 2023.12.17 346
500 [Django] Django 서버를 domain forwarding 시 : Django nginx Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN' 졸리운_곰 2023.12.17 404
499 [Django] Django SSLServer 설정 및 구동 방법 file 졸리운_곰 2023.12.16 288
498 [Python 인터넷] websocket을 이용한 python server에 대용량 파일 전송하기 졸리운_곰 2023.12.14 310
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED