inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[자동화 완전 정복] 인스타그램 휴대폰, 웹 자동화 프로그램 개발

insta_mobile.py 링크만 무한루프 뜹니다. 왜 그런가요?

403

김희수

작성한 질문수 7

0

def insta_mobile_work(device, max_work):
    links = read_links()
    print(links)
    cnt = 1
    for link in links:
        if cnt >= max_work:
            print(link)
            print("이제 작업 종료하겠습니다")
            break
        try:
            visited_links = []  # 이미 좋아요, 댓글, 팔로우를 신청한 링크 리스트
            with open('visited.txt', 'r') as f:
                while True:
                    line = f.readline()
                    if not line:
                        break
                    _link = line.rstrip()
                    visited_links.append(_link)
            if link in visited_links:
                print("이미 방문한 링크입니다.")
                continue
            print(f"{cnt} 번째 링크 방문 {link}")
            # link = link.replace("https://","")
            device.press('home')
            device.open_url(link)
            time.sleep(0.2)
            if device(text="작업을 수행할 때 사용하는 애플리케이션").exists(timeout=2):
                # 삭제되었거나, 잘못된 URL 저장된 경우에 continue
                continue

            ''' visited_account check
                목표 : 최대 3회까지 계정 방문하는 기능
            '''
            visited_accounts = []
            with open('./visited_account.txt', "r") as f:
                while True:
                    line = f.readline()
                    if not line:
                        break
                    account = line.rstrip()
                    visited_accounts.append(account)
            # 몇 번 방문했는지 정보 획득
            account_id = device(resourceId="com.instagram.android:id/row_feed_photo_profile_name").get_text()
            visited_count = visited_accounts.count(account_id)

            if visited_count >= 3:
                # 3회 이상 방문일 때는 다음 링크를 방문하도록 한다
                # continue가 실행되면 여기 밑에있는 코드가 실행이 안됨 (for 문 안에서 사용가능)
                continue

            ''' 1. 좋아요 누르기 - 단, 좋아요가 이미 눌러져 있으면 Pass '''
            # 좋아요 버튼 나타나는것 기준으로 5초까지 대기
            if not device(resourceId="com.instagram.android:id/row_feed_button_like").exists(timeout=3):
                device.swipe_ext("up", scale=0.75)
                time.sleep(3)
            alreadyLiked = False
            if device(resourceId="com.instagram.android:id/row_feed_button_like").exists(
                    timeout=5):  # 만약 ,좋아요 버튼이 안 눌러져있으면 좋아요 버튼을 누른다
                if device(resourceId="com.instagram.android:id/row_feed_button_like", selected=False):
                    device(resourceId="com.instagram.android:id/row_feed_button_like").click()
                    time.sleep(1)
                    if check_bot_detection(device):
                        print("[봇 탐지] - 좋아요 시도 실패")
                        raise Exception("[봇 탐지] - 좋아요 시도 실패")
                else:
                    alreadyLiked = True
            time.sleep(3)

            # ''' # 2. 댓글 달기 - 랜덤 멘트를 미리 작성해놓고, 랜덤으로 뽑아서 댓글 달기'''
            # if not alreadyLiked:
            #     device(resourceId="com.instagram.android:id/row_feed_button_comment").click()
            #     time.sleep(3)
            #     # 기본 키보드가 활성화 되어있는 경우 back버튼을 눌러줌
            #     if device(resourceId="com.samsung.android.honeyboard:id/bee_item_icon").exists():
            #         device.press('back')
            #         time.sleep(1)
            #     if not device(text="이 게시물에 대한 댓글 기능이 제한되었습니다.").exists():
            #         print("커멘트 작성 가능 exists")
            #         device(resourceId="com.instagram.android:id/layout_comment_thread_edittext").click()
            #         # 실제 사람이 작성하는 것처럼 문장 사이의 타이핑 딜레이가 들어감
            #         comments = ["♡", "❤️", "❤️❤️", "♥"]
            #         comment = random.choice(comments)
            #         for word in comment:
            #             device.send_keys(word)
            #             time.sleep(random.uniform(0.03, 0.08))
            #         print("댓글 작성 완료")
            #         time.sleep(3)
            #         if device(
            #                 resourceId="com.instagram.android:id/layout_comment_thread_post_button_click_area").exists():
            #             device(
            #                 resourceId="com.instagram.android:id/layout_comment_thread_post_button_click_area").click()
            #         elif device(resourceId="com.instagram.android:id/layout_comment_thread_post_button").exists():
            #             device(resourceId="com.instagram.android:id/layout_comment_thread_post_button").click()
            #         time.sleep(1)
            #         if check_bot_detection(device):
            #             print("[봇 탐지] - 댓글 달기 시도 실패")
            #             raise Exception("[봇 탐지] - 댓글 달기 시도 실패")
            #         print("게시 버튼 꾸욱.")
            #         time.sleep(2)
            #         device.press('back')
            #         time.sleep(2)
            #         device.press('back')
            #     else:
            #         device.press('back')
            # time.sleep(3)

            # 방문 1회 추가 !
            with open('./visited_account.txt', "a") as f:
                f.write(f"{account_id}\n")

            # 3. 팔로우 신청 - 단, 이미 팔로잉 상태면 Pass
            # 사진 사이즈가 너무 크면, 위로 스와이프 해줘야함
            device.swipe_ext("down", scale=0.8)
            time.sleep(3)

            account_ids = []  # 이미 팔로우를 신청한 계정 리스트
            with open('accounts.txt', "r") as f:
                while True:
                    line = f.readline()
                    if not line:
                        break
                    account_id = line.rstrip()
                    account_ids.append(account_id)
            if not device(resourceId="com.instagram.android:id/row_feed_photo_profile_name").exists():
                device.press('back')
                time.sleep(1)
            target_account_id = device(resourceId="com.instagram.android:id/row_feed_photo_profile_name").get_text()
            # 딱 1번만 팔로우 하겠다.
            if not target_account_id in account_ids:
                # 팔로우할 유저의 계정을 기록
                with open('accounts.txt', "a") as f:
                    account_id = device(resourceId="com.instagram.android:id/row_feed_photo_profile_name").get_text()
                    f.write(f"{account_id}\n")
                device(resourceId="com.instagram.android:id/row_feed_photo_profile_name").click()

                time.sleep(3)
                if device(description="맞팔로우 하기", text="맞팔로우").exists():
                    device(description="맞팔로우 하기", text="맞팔로우").click()
                elif device(text="팔로우", className="android.widget.Button"):
                    device(text="팔로우", className="android.widget.Button").click()
                else:
                    # 이미 맞 팔로우가 되어 있으므로 실행시키지 않아도 됨
                    pass
                time.sleep(1)
                if check_bot_detection(device):
                    print("[봇 탐지] - 팔로우, 맞팔로우 신청 시도 실패")
                    raise Exception("[봇 탐지] - 팔로우, 맞팔로우 신청 시도 실패")
                time.sleep(2)
                device.press("back")
                time.sleep(2)
                device.press("back")
                time.sleep(3)
            else:
                print("이미 팔로우된 계정입니다")
            cnt += 1

            random_time = random.randrange(60, 90)
            print(random_time, '초만큼 대기하겠습니다')
            time.sleep(random_time)
            '좋아요, 팔로우, 댓글 작성까지 완료된 게시글'
            with open('visited.txt', 'a') as f:
                f.write(f"{link}\n")

        except:
            pass

1 번째 링크 방문 https://www.instagram.com/p/C2DUpJJBWI1/

1 번째 링크 방문 https://www.instagram.com/p/C3SMeJSyIRC/

1 번째 링크 방문 https://www.instagram.com/p/C3fDCYiM4gt/

1 번째 링크 방문 https://www.instagram.com/p/C2hjVjmxPEg/

왜그런가요?

python selenium

답변 2

0

김지유

현재 사용중이신 모바일 디바이스 모델과 uiautomator2 version도 함께 알려주시면 감사하겠습니다

0

김희수

모바일 좋아요가 안눌립니다..

0

김희수

uiautomator2를 낮은버전으로 하면 되었다가 또 다음날 오면 안됩니다 이거 왜그런건가요?

site:instagram.com -inurl:explore/tags -inurl:p -inurl:reel intitle:'{keyword}'" 이 코드는 이제 최신게시물을 불러오지 못합니다.

0

217

1

weditor에서

0

253

2

핸드폰으로 자동 클릭안됩니다.

0

547

2

로긴할 때 폰으로 보안코드 보낸거 입력하라는거요..

0

219

1

폰에 atx라는 자동차 모양 아이콘의 앱이 설치되었어요.

0

344

2

팔로워 리스트 추출완료 count 관련 문의드립니다.

0

424

2

휴대폰 로그인 패턴

0

267

2

리스트 추출만 반복

0

395

2

해시태그 검색 후 최근게시물 없음

0

2541

2

에러 확인 좀 부탁드립니다.

0

319

2

해시태그 검색 결과가 수강 내용과 달라서 올려주신 최종 코드가 적용되지 않고 오류가 납니다.

0

538

2

아직 질문 해결이 되지 못했습니다.

0

409

2

https://www.instagram.com/explore/tags/{keyword} 이상해요

0

522

2

윈도우와 맥 환경이 다른 점이 많아서 초기 환경설정부터 막혀있습니다 ㅜ

1

689

2

인스타 검색 부분이 변경 되어서...

1

466

2

Web 태그 접속후, 최근 사진 없습니다.?

0

381

2

계속 안됩니다..

1

321

2

insta_web 질문 있습니다!

1

1644

3

섹션6-3 '댓글' 질문드립니다!

1

359

2

해시태그 추출

1

756

1

인스타그램 로그인 완료 후 검색 부분 (섹션 5 -3)

1

410

1

로그인 이후 발이 묶여서 멈추고 더이상 넘어가지 못하고 있습니다.

1

1092

3

MVWAER 질문 있습니다

0

315

1

모바일 인스타그램 접속 관련 질문

1

320

1