• 카테고리

    질문 & 답변
  • 세부 분야

    업무 자동화

  • 해결 여부

    미해결

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

24.02.21 12:52 작성 조회수 125

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/

왜그런가요?

답변 2

·

답변을 작성해보세요.

0

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

0

김희수님의 프로필

김희수

질문자

2024.02.21

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

김희수님의 프로필

김희수

질문자

2024.02.22

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