Python3.x
前提・実現したいこと
下記サイトからスクレイピングで各求人の仕事内容・求められるスキルを取得したい
発生している問題・エラーメッセージ
stale element reference: element is not attached to the page document
該当のソースコード
#モジュールのインポート from selenium import webdriver import os from bs4 import BeautifulSoup import pandas as pd import requests from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By #取得したい要素(職業名や仕事内容)の変数定義 job_cards = 'a.catch' job_names = 'h2.job' job_descriptions = 'div.jobCatch' job_requirements_musts = 'div.mustSet' next_bottun = 'a.btn.next' #webdriverの設定・URLへ遷移・要素が読み込まれるまでの待機時間の設定 driver = webdriver.Chrome(executable_path="C:...") url = 'https://en-ambi.com/' wait = WebDriverWait(driver, 10) driver.get(url) def main(): while True: #次へボタンがあるまで繰り返し if len(driver.find_element_by_css_selector(next_bottun).text) > 0: #ページ内の求人詳細に遷移する要素の全取得 cards = driver.find_elements_by_css_selector(job_cards) for card in cards: #↑で取得した要素をクリックし遷移したページで下記処理を行う try: card.click() #恐らくここまでは正常に動いていて下記から上手く処理できずエラーが起こっている wait.until(EC.presence_of_element_located((By.ID, "descBase"))) job_name = driver.find_element_by_css_selector(job_names).text #職業名をテキストで取得する job_description = driver.find_element_by_css_selector(job_descriptions).text job_requirements_must = driver.find_element_by_css_selector(job_requirements_musts).text se = pd.Series([job_name,job_description,job_requirements_must],['job_name','job_description','job_requirements_must',]) df = pd.DataFrame() df = df.append(se,ignore_index=True) driver.back() except Exception as e:# -*- coding: utf-8 -*- print(e) next = driver.find_element_by_css_selector(next_bottun).get_attribute("href") #ページ内の次へボタンの要素を取得 driver.get(next) else: print('No page') break df.to_csv('output.csv') print('finish') if __name__ == '__main__': main()
試したこと
取得したい要素のクラス名の修正等してみたのですが上手くいかず・・
回答2件
あなたの回答
tips
プレビュー