Q&A
【目的】
スクレイピングで要素のテキストを取り出したい
【コード】
importは省略
chromedriver = 'chromedriver.exe' URL = 'https://www.makuake.com/project/taiyo19/communication/supporter/' chrome_service = fs.Service(executable_path=chromedriver) driver = webdriver.Chrome(service=chrome_service) driver.get(URL) sleep(3) #ブラウザの高さを取得 win_height = driver.execute_script('return window.innerHeight') #開始位置の初期値 last_top = 1 #ページ最下部までスクロールする(無限) while True: #スクロール前のページの高さを取得 last_height = driver.execute_script('return window.document.body.scrollHeight') #while分での開始位置の設定 top = last_top #html解析 all_date = [] all_user = [] all_coments = [] #取得したいテキスト全体 tags = driver.find_elements(By.XPATH, '//section[@class="post"]') #1つひとつ要素を取り出しテキストへ for tag in tags: dates = tag.find_element(By.XPATH, '//p[@class="postUserNameDate"]') users = tag.find_element(By.XPATH, '//h5') coments = tag.find_element(By.XPATH, '//p[@class="postText-inner"]') all_date.append(dates.text) all_user.append(users.text) all_coments.append(coments.text) sleep(5) #ページを徐々にスクロールする while top < last_height: top += int(win_height * 0.8) driver.execute_script('window.scrollTo(0, %d)' % top) sleep(1) #スクロール後の高さの取得 sleep(1) new_last_height = driver.execute_script('window.document.body.scrollHeight') #同じ高さになったら終了 if last_height == new_last_height: driver.quit() break #開始地点の更新 last_top = last_height
【問題点】
tags = driver.find_elements(By.XPATH, '//section[@class="post"]') for tag in tags: dates = tag.find_element(By.XPATH, '//p[@class="postUserNameDate"]') users = tag.find_element(By.XPATH, '//h5') coments = tag.find_element(By.XPATH, '//p[@class="postText-inner"]') all_date.append(dates.text) all_user.append(users.text) all_coments.append(coments.text)
ここのコードで、tagsにはいくつかのオブジェクトが含まれており、
for tag in tags: print(tags.text)
とやると目的としたテキストがそれぞれ取得できています。
しかし、上記のようにXPATHで要素を指定するとすべて1つ目に取得した要素のテキストに変わってしまいます。
XPATHの'//タブ名[@属性名]'は対象とするタブで共通している部分になります
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2022/06/10 05:38