Selenium instagram


Posted by chenchih on 2021-06-24

今天想分享用Selenium 這個module 來自動登入instgram。我會三種方式給大家,大家可以自行決定要用那一個比較好。
我會用: 最基本的、用class 方式、把登入寫成另外一檔案

基本instagram login

1. import module

  • 如果要用selenium 一定要用selenium 這個module
  • getpadd module 的目的是當你輸入密碼,會被隱藏。

2. driver

from selenium import webdriver
import time, os
from webdriver_manager.chrome import ChromeDriverManager
from getpass import getpass

方法之1:就不用擔心Chromedriver 版本不一樣。
driver = webdriver.Chrome(ChromeDriverManager().install())
方法之2: 如果你Chrome跟chromedriver版本不一樣會有問題,可能要再下載同版本

path='chromedriver.exe'
driver = webdriver.Chrome(path)

3. 登入instgram 和找相關element

請去分析看他的login是用什麼element,如下面我們用 name這個參數,你們也可以用xpath。

  • fiind_element_by_name: 下面那我打算用name,所以就會用到: find_element_by_name 也可以用 find_elements_by_xpath
    請寄的element有分兩種,有s跟沒有s,find_element or find_elements。

    name方式:
    driver.get("https://www.instagram.com/")
    time.sleep(2) 
    user_id=input('Enter Your Username:')
    password=getpass('Enter Password:')
    user_box = driver.find_element_by_name("username")  # For detecting the user id box
    user_box.send_keys('chenchih.test')                     # Enter the user id in the box
    password_box = driver.find_element_by_name("password")   
    password_box.send_keys(password)  
    login_box = driver.find_elements_by_xpath('//*[@id="loginForm"]/div/div[3]')[0]
    login_box.click()
    time.sleep(4)
    
    Xpath 方式:
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input').clear()
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input').send_keys(instgram_login.userID)
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input').clear()
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input').send_keys(instgram_login.userPWD)  
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button').click()    
    time.sleep(10)
    

4. 關掉chrome

可以選擇用
driver.close()

driver.quit()

Class 方法

1. Module

from selenium import webdriver
from time import sleep
from getpass import getpass
from datetime import datetime

2. 加class式

class InstaBot:
    def __init__(self,username,password):
    self.username=username
    self.password=password
    driverPath = 'D:\\test\\chromedriver.exe'
    self.browser.get("http://instagram.com")
    self.browser.find_element_by_name("username").send_keys(username)
    password_box = self.browser.find_element_by_name("password")   # For detecting the password box
    password_box.send_keys(password) 
    self.browser.find_element_by_xpath('//button[@type="submit"]').click()

3. 主程式呼叫class

user_id=input('Enter Your Username:')
password=getpass('Enter Password:')
mybot=InstaBot(user_id, password)
mybot.get_unfollower()

分兩個檔案

1. 把driver login放在這個程式 Filename: instgram_login.py

import time, sys
from selenium import webdriver
try:
    # Chrome with https
    Path_ = 'D:\\chromedriver.exe'    
    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    #options.add_argument('start-maximized')
    driver = webdriver.Chrome(Path_, chrome_options=options)   
    driver.get("https://www.instgram.com/")
    time.sleep(3)
    #find username text id
    userID = input("Please Enter your UserName: ")
    userPWD=getpass("Please Enter your Password: ")        
except:
    print ("Select browser fail")
    driver.quit()
    sys.exit(1)

def login():
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input').clear()
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input').send_keys(userID)
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input').clear()
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input').send_keys(userPWD)  
    driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button').click()    
    time.sleep(10)


def loginNew():
    #################################
    # find the email input and send the email or phone credential
    user_box = driver.find_element_by_name("username")  # For detecting the user id box
    user_box.clear()
    user_box.send_keys(userID)                     # Enter the user id in the box

    # send the password
    password_box = driver.find_element_by_name("password")   # For detecting the password box
    password_box()
    password_box.send_keys(userPWD)                    # For detecting the password in the box

    # click the login
    login_box = driver.find_elements_by_xpath('//*[@id="loginForm"]/div/div[3]')[0]
    login_box.click()
    # or
    #driver.find_element_by_xpath("//button/div[text()='Log In']").click()

    #print(f"Login succes, welcome{user_id}, 5 second will quit")
    time.sleep(2) 
    #store account

    store_click_account  = driver.find_elements_by_xpath('//*[@id="react-root"]/section/main/div/div/div/div/button')[0]
    store_click_account.click()
    #notifcication_click)
    notification_click1  = driver.find_elements_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]')[0]
    notification_click1.click()

driver.find_element_by_xpath("//button/div[text()='Log In']").click() 也可以用,用text找相關文字,但是網頁必須是英文。如果你的instgram是中文,可以用這樣方式: driver.find_element_by_xpath('//button[text()= "登入" or text()= "'Log In'"]').click()
我下面會放用option可以改他的語言,也是 一個方法。

2. 把你要跑的程式放在這 Filename: IG.py

import instgram_login
# -*- coding: utf-8 -*-
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, sys
def StopTest(msg):
    print (msg)
    #weblogin.driver.quit()
    instgram_login.driver.quit()
    sys.exit()    
try:   
    instgram_login.login()    
except:
    StopTest("Connect Fail")

print("Login IN Success")
time.sleep(1)
#weblogin.driver.quit()
instgram_login.driver.quit()
'Log In'

我想補充一些option 參數 東西

如果我們要用text()方式找出相關文字,可是如果你的Instagram是中文就找不到。我們可以打它改成英文。我這影兩種方式
Option 方式

from selenium.webdriver.support.select import Select
option = webdriver.ChromeOptions()
option.add_argument('--lang=en-US')
browser=webdriver.Chrome('D:\\chromedriver.exe',chrome_options=option)

另外一個方法是用click,下面可以選語言:

dropdown = browser.find_element_by_xpath("//*[@id='react-root']/section/footer/div/div[2]/div[1]/span/select")
#dropdown.click()
sel=Select(dropdown)
sel.select_by_visible_text('中文(台灣)')
sel.select_by_visible_text('English')
sel.select_by_value('zh-tw')

或是

browser=webdriver.Chrome('D:\\chromedriver.exe',chrome_options=option)
dropdown = browser.find_element_by_class_name('hztqj')
for option in dropdown.find_elements_by_tag_name('option'):
    if option.text == '中文(台灣)':
        option.click() # select() in earlier versions of webdriver
        break

#selenium #Automation #Python







Related Posts

[第九週] 從 PHP 連線到 MySQL 資料庫

[第九週] 從 PHP 連線到 MySQL 資料庫

GraphQL(1) - 簡介 & 語法

GraphQL(1) - 簡介 & 語法

剛進 Lab 的碩 0

剛進 Lab 的碩 0


Comments