LoginSignup
4
5

More than 3 years have passed since last update.

[Python]Seleniumで動的に変化する属性をXPATH(またはCSSセレクタ)で指定する

Posted at

スクレイピングをする際に属性が動的に変化する要素を指定する際のノウハウ。

HTMLサンプル

<input id="sample_123456789">

このような要素を毎回指定したいケースはよくあると思いますがXPATHかCSSセレクタを使用すると動的に指定する事が出来ます。

XPATHを使用する

element = driver.find_elements_by_xpath('//*[starts-with(@id,"sample_")]')

このように記述すると動的に指定する事が出来ます。

CSSセレクタを使用する

element = driver.find_elements_by_css_selector("input[id^=sample_]")
element = driver.find_elements_by_css_selector("input[id*=sample_]")

CSSセレクタでも同様に指定出来るみたいです。

参考リンク

要素特定のテクニック
【Selenium】動的に変わるidの取得方法
python selenium: iterate through radio buttons that have dynamic ids and select

4
5
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
4
5