質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
スクレイピング

スクレイピングとは、公開されているWebサイトからページ内の情報を抽出する技術です。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

selenium

Selenium(セレニウム)は、ブラウザをプログラムで作動させるフレームワークです。この原理を使うことにより、ブラウザのユーザーテストなどを自動化にすることができます。

Q&A

1回答

746閲覧

Instagram内のclassが見つからない

suzukix

総合スコア0

スクレイピング

スクレイピングとは、公開されているWebサイトからページ内の情報を抽出する技術です。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

selenium

Selenium(セレニウム)は、ブラウザをプログラムで作動させるフレームワークです。この原理を使うことにより、ブラウザのユーザーテストなどを自動化にすることができます。

0グッド

0クリップ

投稿2022/06/03 02:20

解決したいこと

ブログで拾ったインスタグラムでスクレイピングするコードを動かしてみたのですが、
classが変わっていることが原因なのか処理が先に進まなくて困っています。
インスタ内のどこのclassを埋め込めば動くのかご教授いただきたいです。

その他必要な情報などあればご連絡ください。

発生している問題(処理がループする)

06/03/2022 10:49:55 AM - selenium.webdriver.remote.remote_connection - DEBUG - POST http://127.0.0.1:54853/session/238f9d6d61273843fcfec47e8270c275/element/a72aded8-3059-4d4d-a5b4-c041ccbcca10/click {"id": "a72aded8-3059-4d4d-a5b4-c041ccbcca10"}06/03/2022 10:49:55 AM - urllib3.connectionpool - DEBUG - http://127.0.0.1:54853 "POST /session/238f9d6d61273843fcfec47e8270c275/element/a72aded8-3059-4d4d-a5b4-c041ccbcca10/click HTTP/1.1" 200 14 06/03/2022 10:49:55 AM - selenium.webdriver.remote.remote_connection - DEBUG - Finished Request

困っているソースコード(部分)

Python

1 2def waitElementClickable(elementLocator, seconds): 3 wait = WebDriverWait(driver, 30) 4 element = wait.until(expected_conditions.element_to_be_clickable(elementLocator)) #ここの処理がループする。 5 time.sleep(seconds) 6 return element 7 8 laterButtonXpath = "//button[@='.rq0escxv.l9j0dhe7.du4w35lb']" #現時点のこの部分のclassが取得できてない模様 9 elementLaterButton = waitElementClickable((By.XPATH, laterButtonXpath), 2) 10 elementLaterButton.click() 11 time.sleep(random.randint(2, 3)) 12 13 laterButtonXpath2 = "//button[@class='.j83agx80.cbu4d94t.d6urw2fd.dp1hu0rb.l9j0dhe7.du4w35lb']" #おそらくここも取得できない。 14 elementLaterButton2 = waitElementClickable((By.XPATH, laterButtonXpath2), 2) 15 elementLaterButton2.click() 16 time.sleep(random.randint(2, 3)) 17 startAutomation()

ソースコード全体)

ruby

1from selenium import webdriver 2from selenium.common.exceptions import WebDriverException 3from selenium.webdriver.common.action_chains import ActionChains 4from selenium.webdriver.support.ui import WebDriverWait 5from selenium.webdriver.support import expected_conditions 6from selenium.webdriver.common.by import By 7from datetime import datetime 8import os 9import time 10import random 11import logging.config 12from logging.config import fileConfig 13import logging 14 15 16likeCounter = 0 17notLikeCounter = 0 18alreadyLikeCounter = 0 19continueLikeTooMuchCounter = 0 20continuousLikeCounter = 0 21error_flg = False 22 23def login(): 24 driver.get('https://www.instagram.com/accounts/login/?source=auth_switcher') 25 time.sleep(1) 26 userNameTextBoxName = 'username' 27 passTextBoxName = 'password' 28 elementUserNameTextBox = waitElement((By.NAME, userNameTextBoxName), 2) 29 elementUserNameTextBox.send_keys('ユーザー名') 30 time.sleep(1) 31 driver.find_element_by_name(passTextBoxName).send_keys('パスワード') 32 time.sleep(1) 33 34 #driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]').click() 35 loginButtonClassName = 'L3NKy ' 36 elementLoginButton = waitElementClickable((By.CLASS_NAME, loginButtonClassName), 2) 37 elementLoginButton.click() #class="sqdOP L3NKy y3zKF " 38 39 if error_flg is False: 40 try: 41 time.sleep(10) 42 driver.find_element_by_xpath('//button[text()="後で"]').click() 43 except Exception: 44 pass 45 46 if error_flg is False: 47 try: 48 time.sleep(10) 49 driver.find_element_by_xpath('//button[text()="後で"]').click() 50 except Exception: 51 pass 52 53 54def searchByTag(tag): 55 logger.info('search by {}'.format(tag)) 56 instaurl = 'https://www.instagram.com/explore/tags/' 57 driver.get(instaurl + tag) 58 time.sleep(random.randint(2, 5)) 59 60 target = driver.find_elements_by_class_name('_9AhH0')[10] 61 actions = ActionChains(driver) 62 actions.move_to_element(target) 63 actions.perform() 64 time.sleep(random.randint(2, 5)) 65 66def isAlreadyPressLike(likeButton): 67 label = likeButton.get_attribute('aria-label') 68 if label == '「いいね!」を取り消す': 69 return True 70 else: 71 return False 72 73def pressLike(): 74 global likeCounter 75 global alreadyLikeCounter 76 global continueLikeTooMuchCounter 77 global continuousLikeCounter 78 likeButtonClassName = 'fr66n' 79 elementLikeButton = waitElementClickable((By.CLASS_NAME,likeButtonClassName) , 2) 80 element = elementLikeButton.find_element_by_xpath('./button/div/span') 81 element1 = element.find_element_by_class_name('_8-yf5 ') 82 if isAlreadyPressLike(element1): 83 time.sleep(1) 84 alreadyLikeCounter = alreadyLikeCounter + 1 85 logger.info('already press like_{}'.format(alreadyLikeCounter)) 86 continuousLikeCounter = 0 87 else: 88 if continuousLikeCounter >= 10: 89 time.sleep(1) 90 continueLikeTooMuchCounter = continueLikeTooMuchCounter + 1 91 logger.info('pressed like continuously {} times, so not press like. This is {} times.'.format(continuousLikeCounter, continueLikeTooMuchCounter)) 92 continuousLikeCounter = 0 93 else: 94 time.sleep(random.randint(2, 5)) 95 elementLikeButton.click() 96 likeCounter = likeCounter + 1 97 continuousLikeCounter = continuousLikeCounter + 1 98 logger.info('press like_{}'.format(likeCounter)) 99 100def clickLike(): 101 global notLikeCounter 102 global continuousLikeCounter 103 targetImageClassName = '_9AhH0' 104 elementtargetImages = waitElements((By.CLASS_NAME,targetImageClassName) , 2) 105 elementImageToScroll = elementtargetImages[10] 106 actions = ActionChains(driver) 107 actions.move_to_element(elementImageToScroll) 108 actions.perform() 109 time.sleep(random.randint(2, 3)) 110 111 driver.find_elements_by_class_name(targetImageClassName)[9].click() 112 time.sleep(random.randint(2, 3)) 113 114 pressLikeLoopCount = random.randint(5, 6) 115 for pressLikeLoopCounter in range(pressLikeLoopCount): 116 if random.randint(1, 6) % 6 == 0: 117 notLikeCounter += 1 118 continuousLikeCounter = 0 119 logger.info('not to try press like_{}'.format(notLikeCounter)) 120 time.sleep(1) 121 else: 122 pressLike() 123 time.sleep(random.randint(2, 3)) 124 125 if pressLikeLoopCounter == pressLikeLoopCount - 1: 126 break 127 128 nextArrowClassName = 'coreSpriteRightPaginationArrow' 129 elementNextArrow = waitElementClickable((By.CLASS_NAME, nextArrowClassName), 2) 130 elementNextArrow.click() 131 time.sleep(random.randint(2, 5)) 132 133def convertMinutesToSeconds(minutes): 134 return (minutes * 60) 135 136def waitElement(elementLocator, seconds): 137 wait = WebDriverWait(driver, 10) 138 element = wait.until(expected_conditions.presence_of_element_located(elementLocator))  139 time.sleep(seconds) 140 return element 141 142def waitElements(elementLocator, seconds): 143 wait = WebDriverWait(driver, 10) 144 elements = wait.until(expected_conditions.presence_of_all_elements_located(elementLocator)) 145 time.sleep(seconds) 146 return elements 147 148def waitElementClickable(elementLocator, seconds): 149 wait = WebDriverWait(driver, 30) 150 element = wait.until(expected_conditions.element_to_be_clickable(elementLocator)) #ここの処理がループする。 151 time.sleep(seconds) 152 return element 153 154def startAutomation(): 155 global continuousLikeCounter 156 157 topLoopCount = random.randint(5, 6) 158 for topLoopCounter in range(topLoopCount): 159 continuousLikeCounter = 0 160 searchByTag(random.choice(taglist)) 161 clickLike() 162 if topLoopCounter == topLoopCount - 1: 163 break#最後のループは待機せずブラウザを閉じに行く 164 time.sleep(random.randint(15, 30)) 165 166if __name__ == '__main__': 167 taglist = ['ワード1', 'ワード2'] 168 logging.config.fileConfig('logging.conf',disable_existing_loggers=False) 169 logger = logging.getLogger() 170 171 loopCount = 0 172 errorCount = 0 173 logging.info('Start!!!') 174 while True: 175 try: 176 driver = webdriver.Chrome( 'chromedriver.exeの格納先') 177 loopCount += 1 178 logging.info('Loop Count_{}'.format(loopCount)) 179 login() 180 time.sleep(random.randint(2, 3)) 181 182 #laterButtonXpath = "//button[@class='.sqdOP.yWX7d.y3zKF']" 183 laterButtonXpath = "//button[@='.rq0escxv.l9j0dhe7.du4w35lb']" #現時点のこの部分のclassが取得できてない模様 184 elementLaterButton = waitElementClickable((By.XPATH, laterButtonXpath), 2) 185 elementLaterButton.click() 186 time.sleep(random.randint(2, 3)) 187 188 #laterButtonXpath2 = "//button[@class='.aOOlW.HoLwm']" 189 laterButtonXpath2 = "//button[@class='.j83agx80.cbu4d94t.d6urw2fd.dp1hu0rb.l9j0dhe7.du4w35lb']" #おそらくここも取得できない。 190 elementLaterButton2 = waitElementClickable((By.XPATH, laterButtonXpath2), 2) 191 elementLaterButton2.click() 192 time.sleep(random.randint(2, 3)) 193 startAutomation() 194 except Exception as e: 195 errorCount += 1 196 import traceback 197 logging.error(traceback.format_exc()) 198 199 screenShotFileName = '{}errorImage{}.png'.format(datetime.now().strftime("%Y%m%d_%H%M%S") , errorCount) 200 screenShotFloderPath = os.path.dirname(os.path.abspath(__file__)) 201 screenShotFullPath = os.path.join(screenShotFloderPath, screenShotFileName) 202 driver.save_screenshot(screenShotFullPath) 203 204 if errorCount == 10: 205 logging.error('Error. End system.') 206 driver.close() 207 break 208 209 logging.error('error {} times'.format(errorCount)) 210 driver.close() 211 waitTime = random.randint(convertMinutesToSeconds(60), convertMinutesToSeconds(65)) 212 logging.info('wait for {} secs'.format(waitTime)) 213 time.sleep(waitTime) 214 else: 215 if loopCount % 10 == 0: 216 waitTime = random.randint(convertMinutesToSeconds(30), convertMinutesToSeconds(32)) 217 logging.info('wait for {} secs'.format(waitTime)) 218 driver.close() 219 time.sleep(waitTime) 220 else: 221 waitTime = random.randint(convertMinutesToSeconds(10), convertMinutesToSeconds(12)) 222 logging.info('wait for {} secs'.format(waitTime)) 223 driver.close() 224 time.sleep(waitTime) 225 226 227

自分で試したこと

もともとのコードは以下のようになっていたのですが、見つからなかったのでその他classで試してみましたが見つかりませんでした。
laterButtonXpath = "//button[@class='.sqdOP.yWX7d.y3zKF']"

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

そもそも論として、Instagramのスクレイピングは利用規約違反です。

不正な方法を用いて、アカウントの作成、情報へのアクセス、または情報の取得を試みることは禁止されています。
これには、弊社から明示的な許可を得ることなく、自動化された手段を用いてアカウントを作成したり、情報を取得したりする行為が含まれます。(強調も原文ママ)

投稿2022/06/03 02:30

maisumakun

総合スコア145123

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問