LoginSignup
6

More than 5 years have passed since last update.

Capybara で得た要素の innerHTML を取得する

Posted at

Capybara の find 使ってて、以下のようなエラーに遭遇することってありますよね。

> find('li.userList')
=> Capybara::Ambiguous: Ambiguous match, found 2 elements matching css "li.userList"

セレクタが曖昧で、2件ヒットしちゃったワケです。

ひとつめを取得するにはこうすればいいです。

> find_all('li.userList')[0]
=> #<Capybara::Node::Element tag="li" path="/html/body/div/div[2]/section/div[7]/div/div[1]/ul/li[1]">

とはいえその html がどういうふうになっているのか、やっぱ知りたいですよね。曖昧なセレクタは良くない。

というワケで、html を取得するには Capybara::Node::Element#native を使えば良いですよ。というハナシ。

> find_all('li.userList')[0].native.to_s
=> "<li class=\"userList\">\n< ……略……

参考にしたページ

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
What you can do with signing up
6