파이썬(Python)/인스타그램

인스타그램 자동 로그인 (Instagram Log in)

끄적끄적아무거나 2020. 12. 1. 19:16
반응형

코드>>

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
import time

def log_in():
    options = webdriver.ChromeOptions() 
    # options.headless = True
    options.add_experimental_option("excludeSwitches", ["enable-logging"])
    # options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
    # /AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36")
    driver = webdriver.Chrome(options=options)
    driver.get("https://www.instagram.com/")

    # time.sleep(3)

    try:
        username_box_check = WebDriverWait(driver, 10).until(EC.presence_of_element_located\
            ((By.XPATH, '//*[@id="loginForm"]/div/div[1]/div/label/input')))
        print(username_box_check)
    except:
        print("error")

    username_box = driver.find_elements_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')[0]
    username_box.send_keys("your_id")
    password_box = driver.find_elements_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input')[0]
    password_box.send_keys("your_password!")
    login_button = driver.find_elements_by_xpath('//*[@id="loginForm"]/div/div[3]/button')[0]
    login_button.click()

    time.sleep(100)

log_in()

결과 화면>>

 

 

 

주석>>

우선 코드를 작성하기 전에 인스타에 가입하였다.

 

options.add_experimental_option("excludeSwitches", ["enable-logging"])

위 코드는 Chrome webdriver를 열때 옵션을 추가 한 것이다.

 

정확한 이유는 모르겠지만 내 컴퓨터 내부에 설치 된 프로그램과 충돌 때문인지 아래와 같은 에러메세지가 발생하였다.

[15188:3920:1201/185912.848:ERROR:device_event_log_impl.cc(211)] [18:59:12.849] USB: usb_device_handle_win.cc:1020 Failed to read descriptor from node connection: 시스템에 부착된 장치가 작동하지 않습니다. (0x1F)

 

그래서 구글 검색으로 찾은 해결책이 위 코드이다.

 

주석으로 처리된 user-agent 헤더 추가 부분은 기존의 selenium 같은 경우 user-agent에 크롬자동제어로 표기 되어 사이트 서버에서 거부하는 현상이 있어 직접 헤더를 수정해서 서버 거부를 회피하는 방식이었으나 최근에 업데이트 된 selenium에서는 알아서 user-agent를 webdriver를 사용하지 않은 것처럼 보내 준다.

 

try:

username_box_check = WebDriverWait(driver, 10).until(EC.presence_of_element_located\

((By.XPATH, '//*[@id="loginForm"]/div/div[1]/div/label/input')))

print(username_box_check)

except:

print("error")

 

위 코드는 인스타 메인화면에 들어가도 webdriver가 빨리 접속해버려서 로그인 화면이 내 컴퓨터에 로딩되기전에 입력하는 상황을 피하기 위해 원하는 화면이 로딩 되었는 xpath에서의 주소를 확인하고 만일 10초 동안 xpath 주소가 안뜨면 에러 메세지를 띄우게 만들었다.

 

단순한 방법으로 로딩 시간을 기다리길 원한다면 주석처럼 time.sleep(3)을 사용해서 로딩 될 시간을 주면 된다.

 

그리고 xpath로 인스타그램의 id와 pw에 해당하는 위치를 찾아서 값을 보낸다.

 

이때 주의 할 점은 아래 코드에서 보면 알겠지만 return값은 list로 들어가므로 리스트에서 값을 빼줘야지 위치를 파악한다. 네이버 로그인 같은 경우는 값이 리스트로 나오지 않고 바로 나온다. 여기서 리스트 값을 빼주기 위해 [0]을 넣었다.

 

확인해보고 싶다면 naver에서 로그인 할때 값을 print 해보고 인스타에서도 print해서 비교해보길 바란다.

 

username_box = driver.find_elements_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')[0]

 

 

 

 

 

 

 

 

 

 

반응형