1
1

More than 3 years have passed since last update.

VBAとPythonのSeleniumでvalue属性の値を変更する

Posted at

前置き

何をしたかったのか。
valueの値を変更して、最大値を超えた件数を表示させる。
"次へ""nextBtn"などを探せばいい…?たった数ページのために?
というところから。

いろいろな単語で検索しましたよ、ええ。
python value 置き換え
selenium value 置き換え
select option value 変更

全部だめ。自分が求めていた答えではなかった。
んで、最終的にたどり着いた検索の単語が
selenium value changesetattribute selenium
アメリカ最高!英語検索しか勝たん。
ちなみに英語わからなくても超優秀なDeepl翻訳が何とかしてくれる。
以下、参考にしたサイト。
How to set "value" to input web element using selenium?
RubyのSeleniumでAttributeの値を変更したい

本題

HTML
<!-- リスト -->
<select name="LIST">
    <option value="25" id="LIST">25件</option>
    <option value="50" id="LIST">50件</option>
    <option value="100" id="LIST">100件</option>
    <option value="200" id="LIST">200件</option>
</select>

<!-- 検索ボタン -->
<input type="Search" name="Search" onclick="return SearchCheck()" value="検索する">

上記のようなHTMLだったとして、
<option value="200" id="LIST">200件</option>
<option value="500" id="LIST">200件</option>に変更して検索する。

注意書き

コードを書く前に、実際のページでvalueの値を変更してみて問題ないか確認すること。

Dim Driver As New Selenium.WebDriver
SeleniumBasicがインストールされていると使える。
詳しくは下記URL
VBAからchromeスクレイピング

driver = webdriver.Chrome(ChromeDriverManager().install())
webdriver_managerがインストールされていると使える。
詳しくは下記URLかchromedriver.exeのPATHを通してください。
Python+SeleniumWebDriverではwebdriver_managerを使うといちいちdriverのexeを置き換えなくて済む

VBAでやってみる

VBA
Dim Driver As New Selenium.WebDriver
Driver.Get "https://hoge.jp"

# ------ option value 変更 ------
Dim target_element As Object
Set target_element = Driver.FindElementsById("LIST")(4)
Driver.ExecuteScript "arguments[0].setAttribute('value','500')", target_element

# ------ 変更したvalue を選択、検索 ------
Driver.FindElementByName("LIST").AsSelect.SelectByText "200件"
Driver.FindElementByName("Search").Click

Pythonでやってみる

Python
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://hoge.jp')

# ------ option value 変更 ------
target_element = driver.find_elements_by_id('LIST')[3]
driver.execute_script("arguments[0].setAttribute('value','500')", target_element)

# ------ 変更したvalueを選択、検索 ------
select_element = driver.find_element_by_name('LIST')
list_object = Select(select_element)
list_object.select_by_visible_text('200件')
driver.find_element_by_name("Search").Click
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1