• 카테고리

    질문 & 답변
  • 세부 분야

    업무 자동화

  • 해결 여부

    미해결

insta_web 질문 있습니다!

23.06.05 19:01 작성 조회수 898

1

안녕하세요! 선생님 혹시 에러가 나는데 봐주실 수 있을까요 ㅠㅠ 기본적으로 로그인부터 안됩니다 ㅠㅠ

에러

DevTools listening on ws://127.0.0.1:51221/devtools/browser/d2c4970f-37a8-4257-ad60-95407a9b0e45

cannot access local variable 'actions' where it is not associated with a value

[에러] insta_web_login > 에러 발생

Traceback (most recent call last):

File "c:\Users\문소희\Desktop\project\insta_auto\main.py", line 25, in <module>

insta_web.insta_web_work(driver,keyword,count)

File "c:\Users\문소희\Desktop\project\insta_auto\insta_web.py", line 117, in insta_web_work

insta_web_link_extract(driver,count)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "c:\Users\문소희\Desktop\project\insta_auto\insta_web.py", line 75, in insta_web_link_extract

WebDriverWait(driver, 10).until(EC.presence_of_element_located(

File "C:\Users\문소희\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\support\wait.py", line 95, in until

raise TimeoutException(message, screen, stacktrace)

selenium.common.exceptions.TimeoutException: Message:

Stacktrace:

Backtrace:

GetHandleVerifier [0x01086E73+48323]

(No symbol) [0x01019661]

(No symbol) [0x00F25308]

(No symbol) [0x00F50B45]

(No symbol) [0x00F50CDB]

(No symbol) [0x00F7E3D2]

(No symbol) [0x00F6A924]

(No symbol) [0x00F7CAC2]

(No symbol) [0x00F6A6D6]

(No symbol) [0x00F4847C]

(No symbol) [0x00F4957D]

GetHandleVerifier [0x012EFD5D+2575277]

GetHandleVerifier [0x0132F86E+2836158]

GetHandleVerifier [0x013296DC+2811180]

GetHandleVerifier [0x011141B0+626688]

(No symbol) [0x0102314C]

(No symbol) [0x0101F4B8]

(No symbol) [0x0101F59B]

(No symbol) [0x010121B7]

BaseThreadInitThunk [0x76A100C9+25]

RtlGetAppContainerNamedObjectPath [0x77907B4E+286]

RtlGetAppContainerNamedObjectPath [0x77907B1E+238]

 

main

import time
import uiautomator2 as u2
from selenium import webdriver

import insta_web
import insta_mobile


serial = "ce031713db01712d02"
device = u2.connect(serial)

options = webdriver.ChromeOptions()
options.add_argument('--user-agent= Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36')
options.add_argument("--disanble-logging")
options.add_experimental_option("useAutomationExtension",False)
options.add_experimental_option('excludeSwitches',["enable-auttomation"])

driver = webdriver.Chrome(options=options)

keyword_list = ["골린이", "골프사랑", "골프중독","골프스윙", "골프레슨"]

for keyword in keyword_list:
    keyword = keyword.replace(" ","")
    count = 1000
    insta_web.insta_web_work(driver,keyword,count)
    insta_mobile.insta_mobile_work(device)

 

insta_web

import time, data
import chromedriver_autoinstaller
chromedriver_autoinstaller.install()

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
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import pyperclip


def insta_web_login(driver):
    try:
        driver.get("https://www.instagram.com/")
        # time.sleep(2)
        id_selector = "#loginForm > div > div:nth-child(1) > div > label > input"

        WebDriverWait(driver, 10).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, id_selector)    
        ))

        id_input = driver.find_element(By.CSS_SELECTOR,id_selector)
        id_input.click()
        time.sleep(5)

       # ctrl + c 동작
        pyperclip.copy(data.id)
        # ctrl + v 동작
        actions.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

        # id_input.send_keys(data.id)
        time.sleep(5)

        pw_selector = "#loginForm > div > div:nth-child(2) > div > label > input"
        pw_input = driver.find_element(By.CSS_SELECTOR,pw_selector)
        pw_input.click()
        time.sleep(5)
        actions = ActionChains(driver)  

        # ctrl + c 동작
        pyperclip.copy(data.pw)
        # ctrl + v 동작
        actions.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

        time.sleep(5)
        login_btn_selector = "#loginForm > div > div:nth-child(3) > button"
        login_btn = driver.find_element(By.CSS_SELECTOR, login_btn_selector)
        login_btn.click(5)
    except Exception as e:
        print(e)
        print('[에러] insta_web_login > 에러 발생')


def insta_web_hashtag_search(driver,keyword):
    try:
            

        time.sleep(50)
        from urllib import parse
        keyword = "골프사랑"
        keyword = parse.quote(keyword)
        driver.get(f"https://www.instagram.com/explore/tags/{keyword}/")
    except Exception as e:
        print(e)
        print["[에러] insta_web_hashtag_search > 해시태그 검색중 에러 발생"]    


def insta_web_link_extract(driver, count=100):
    time.sleep(5)
    all_posting_sel = "div[id^='mount_0_0'] > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.xnz67gz.x78zum5.x168nmei.x13lgxp2.x5pf9jr.xo71vjh.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.x1q0g3np.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xh8yej3.x1gryazu.x10o80wk.x14k21rp.x1porb0y.x17snn68.x6osk4m > section > main > article > div:nth-child(3) > div"
    WebDriverWait(driver, 10).until(EC.presence_of_element_located(
        (By.CSS_SELECTOR, all_posting_sel)    
    ))

    all_posting_box = driver.find_element(By.CSS_SELECTOR, all_posting_sel)
    time.sleep(5)

    '''링크 100개 추출'''

    links = []
    while len(links) < count :
        try:
            for _ in range(6):
                driver.execute_script("window.scrollBy(0,600);")
                time.sleep(5)
        
            all_posting_box = driver.find_element(By.CSS_SELECTOR, all_posting_sel)
            posk_links = all_posting_box.find_elements(By.TAG_NAME,"a")

            for eachLink in posk_links:
                
                link = eachLink.get_attribute('href')
                links.append(link)

        
            links = set(links) 
            links = list(links) 

        except Exception as e:
            print(e)
            print("insta_web_link_extract > while 에러 발생")
           
        

    with open('links.txt',"a") as f:
        for link in links:
            # print(link)
            f.write(f"{link}\n")

def insta_web_work(driver,keyword,count):
    insta_web_login(driver)
    insta_web_hashtag_search(driver, keyword)
    insta_web_link_extract(driver, count)

 

insta_ mobile

import time, data
import chromedriver_autoinstaller
chromedriver_autoinstaller.install()

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
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import pyperclip


def insta_web_login(driver):
    try:
        driver.get("https://www.instagram.com/")
        # time.sleep(2)
        id_selector = "#loginForm > div > div:nth-child(1) > div > label > input"

        WebDriverWait(driver, 10).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, id_selector)    
        ))

        id_input = driver.find_element(By.CSS_SELECTOR,id_selector)
        id_input.click()
        time.sleep(5)

       # ctrl + c 동작
        pyperclip.copy(data.id)
        # ctrl + v 동작
        actions.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

        # id_input.send_keys(data.id)
        time.sleep(5)

        pw_selector = "#loginForm > div > div:nth-child(2) > div > label > input"
        pw_input = driver.find_element(By.CSS_SELECTOR,pw_selector)
        pw_input.click()
        time.sleep(5)
        actions = ActionChains(driver)  

        # ctrl + c 동작
        pyperclip.copy(data.pw)
        # ctrl + v 동작
        actions.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

        time.sleep(5)
        login_btn_selector = "#loginForm > div > div:nth-child(3) > button"
        login_btn = driver.find_element(By.CSS_SELECTOR, login_btn_selector)
        login_btn.click(5)
    except Exception as e:
        print(e)
        print('[에러] insta_web_login > 에러 발생')


def insta_web_hashtag_search(driver,keyword):
    try:
            

        time.sleep(50)
        from urllib import parse
        keyword = "골프사랑"
        keyword = parse.quote(keyword)
        driver.get(f"https://www.instagram.com/explore/tags/{keyword}/")
    except Exception as e:
        print(e)
        print["[에러] insta_web_hashtag_search > 해시태그 검색중 에러 발생"]    


def insta_web_link_extract(driver, count=100):
    time.sleep(5)
    all_posting_sel = "div[id^='mount_0_0'] > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.xnz67gz.x78zum5.x168nmei.x13lgxp2.x5pf9jr.xo71vjh.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.x1q0g3np.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.xh8yej3.x1gryazu.x10o80wk.x14k21rp.x1porb0y.x17snn68.x6osk4m > section > main > article > div:nth-child(3) > div"
    WebDriverWait(driver, 10).until(EC.presence_of_element_located(
        (By.CSS_SELECTOR, all_posting_sel)    
    ))

    all_posting_box = driver.find_element(By.CSS_SELECTOR, all_posting_sel)
    time.sleep(5)

    '''링크 100개 추출'''

    links = []
    while len(links) < count :
        try:
            for _ in range(6):
                driver.execute_script("window.scrollBy(0,600);")
                time.sleep(5)
        
            all_posting_box = driver.find_element(By.CSS_SELECTOR, all_posting_sel)
            posk_links = all_posting_box.find_elements(By.TAG_NAME,"a")

            for eachLink in posk_links:
                
                link = eachLink.get_attribute('href')
                links.append(link)

        
            links = set(links) 
            links = list(links) 

        except Exception as e:
            print(e)
            print("insta_web_link_extract > while 에러 발생")
           
        

    with open('links.txt',"a") as f:
        for link in links:
            # print(link)
            f.write(f"{link}\n")

def insta_web_work(driver,keyword,count):
    insta_web_login(driver)
    insta_web_hashtag_search(driver, keyword)
    insta_web_link_extract(driver, count)

 

답변 3

·

답변을 작성해보세요.

1

김기솔님의 프로필

김기솔

질문자

2023.06.12

actions.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

        # id_input.send_keys(data.id)
        time.sleep(5)

        pw_selector = "#loginForm > div > div:nth-child(2) > div > label > input"
        pw_input = driver.find_element(By.CSS_SELECTOR,pw_selector)
        pw_input.click()
        time.sleep(5)
        actions = ActionChains(driver)  

        # ctrl + c 동작
        pyperclip.copy(data.pw)
        # ctrl + v 동작
        actions.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

이 부분은 어떤 에러인가요?!

1

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.06.07

안녕하세요, 인프런 AI 인턴이에요.

에러 메시지를 보면 로그인 관련 에러가 아니라 insta_web_link_extract 함수에서 발생한 TimeoutException 에러 같습니다. 해당 함수에서는 EC.presence_of_element_located 메소드를 사용하여 element가 나타날 때까지 기다렸다가 실행하는데, TimeoutException은 element가 일정 시간 내에 나타나지 않을 때 발생하는 예외입니다.

해당 에러를 해결하기 위해서는 대기 시간을 늘리거나, 나타날 element의 selector를 정확히 지정하여 대기 시간을 줄이는 등 다양한 방법이 있을 수 있습니다.

현재 드라이버가 정상적으로 동작하는지부터 확인해보시고, 위 방법을 시도해보시길 권장드립니다. 만약에 원하시는 결과가 나오지 않는다면, insta_auto 관련 다른 질문들도 같이 게시글에 올리시면 더욱 적극적인 답변이 가능할 것 같아요.

이상입니다. 좋은 하루 되세요!

0

image

text compare 결과입니다

75번째 라인 코드인

all_posting_sel = "div[id^='mount_0_0'] > div > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.xnz67gz.x78zum5.x168nmei.x13lgxp2.x5pf9jr.xo71vjh.x1uhb9sk.x1plvlek.xryxfnj.x1c4vz4f.x2lah0s.x1q0g3np.xqjyukv.x1qjc9v5.x1oa3qoh.x1qughib > div.x1gryazu.xh8yej3.x10o80wk.x14k21rp.x17snn68.x6osk4m.x1porb0y > section > main > article > div:nth-child(3) > div"

코드 부분을 수정하셔야하는데

 

[해결방법]

아래 사진과 같이 최근사진들의 box가 전체 선택되도록 css_selector를 한번 더 가져오셔야합니다

image

박스 selector 다시 긁어오셔서 all_posting_sel 변수에 넣어주시면 코드 작동합니다 !

미남미녀님의 프로필

미남미녀

2023.06.15

위에서 말씀해주신대로 css_selector을 긁어와서 all_posting_sel 변수에 넣었습니다.

근데 헤시태그 검색후 인기 게시물이 보이고 프로그램이 종료되고있습니다...

미남미녀님의 프로필

미남미녀

2023.06.15

image