Seleniumで全要素が読み込まれるまで待機しても毎回結果が変わってしまう
解決したいこと
PythonとSelenium、BeautifulSoupを使用して、
あるSNSのプロフィールページに遷移→プロフィール内に記載されている各SNSのURLを取得→googleスプレッドシートに出力するという機能を作っています。
1.WebDriverで全要素が読み込まれるまで待機する処理を入れているのですが、毎回結果が違ってしまいます。
2.遷移元SNSでの最終投稿日を取得したいのですが、〇days agoのような表記がされている場合に、変数に値が入ってこず、値が取得できません。
該当するソースコード
Pyython(Google Colab)
i = 0
for row in df.itertuples():
# D列が空欄ならURLから情報を取得
if row.名前 == "" :
url = row.URL
# ページの読み込みを完了まで最大15秒待機
try:
driver.get(url)
WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located)
except TimeoutException:
print("タイムアウトが発生しました。")
html = driver.page_source.encode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
# 名前を取得
user_name = soup.find('div', class_=lambda x: x and 'username' in x)
if(user_name == None) :
df.at[i, '名前'] = ''
else :
df.at[i, '名前'] = user_name.get_text()
a_tags = []
profile_element = soup.find('p', class_=lambda x: x and 'profile' in x)
if (profile_element != None):
a_tags = profile_element.find_all('a')
# URLを一括取得
if(a_tags != None) :
for a_tag in a_tags:
href = a_tag.get('href')
if(href != None) :
# urlにtwitter.comが含まれていたらDFに値を追加
if('twitter.com' in href) :
df.at[i, 'Twitter'] = href
# urlにinstagram.comが含まれていたらDFに値を追加
elif('instagram.com' in href) :
df.at[i, 'Instagram'] = href
# urlにtiktok.comが含まれていたらDFに値を追加
elif('tiktok.com' in href) :
df.at[i, 'TikTok'] = href
# urlにyoutube.comが含まれていたらDFに値を追加
elif('youtube.com' in href) :
df.at[i, 'YouTube'] = href
# urlにその他のURLが含まれていたらDFに値を追加
else :
df.at[i, 'その他URL'] = href
# 最終投稿日を取得
latest_post = soup.find('span',class_=lambda x: x and 'CreatedAt' in x)
if(latest_post == None) :
latest_post = ""
else :
latest_post = latest_post.get_text()
df.at[i, '最終投稿日'] = latest_post
自分で試したこと
いろいろ調べましたが情報が出てこず、手詰まりの状態です。
解決方法が分かる方がいらっしゃいましたら、助けていただけると幸いです。
よろしくお願いいたします。