概要
PythonのSeleniumを使って選択ボックスを操作する方法をまとめる。
選択ボックスとは次のもの。
選択ボックスをクリックすると選択肢が表示されて、クリックするとそのページに変わる。そのような操作を自動でおこないたい。
ソースコード
完全なもの
import os import time import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.common.exceptions import NoSuchElementException # initialize ## which geckodriver DRIVER_PATH = '/usr/local/bin/geckodriver' ## no headless driver = webdriver.Firefox(executable_path=DRIVER_PATH, service_log_path=os.path.devnull) # go to the yahoo page url = 'https://news.yahoo.co.jp/topics/top-picks' driver.get(url) time.sleep(3) # click the select button ## find the element and create an object css_selector = '.newsFeedFilter_select > select:nth-child(1)' select_element = driver.find_element(By.CSS_SELECTOR, css_selector) select_object = Select(select_element) ## click date = '20220330' try: select_object.select_by_value(date) except NoSuchElementException as e: print(e) driver.quit() sys.exit() time.sleep(3) # go back to the top page css_selector = '#msthdLogo > img:nth-child(1)' driver.find_element(By.CSS_SELECTOR, css_selector).click() time.sleep(3) driver.quit()
別解1(インデックスパターン)
... (中略) #### case II: index select_object.select_by_index(2) # 0番目基準(Zero-based numbering) 3月30日(水) ... (中略)
別解2(テキストパターン)
... (中略) #### case III: text select_object.select_by_visible_text('3月30日(水)') ... (中略)
実行結果
前提知識および注意事項
前提知識
- Seleniumをインストールして、自分の環境で一通り動かすことができること。
選択肢のタグを調べる方法