###前提・実現したいこと
rubyでスクレイピングをしたいと考えております。
複数あるtableをeach文で取り出し、各ノードからデータを抽出したいと考えております。
###サンプル
html
1<table class="info"> 2 <tbody> 3 <tr><th>名前</th><td>***********</td></tr> 4 <tr><th>郵便番号</th><td>***********</td></tr> 5 <tr><th>住所</th><td>***********</td></tr> 6 <tr><th>電話番号</th><td>***********</td></tr> 7 <tr><th>担当様</th><td>***********</td></tr> 8 </tbody> 9</table> 10<table class="info"> 11 <tbody> 12 <tr><th>名前</th><td>***********</td></tr> 13 <tr><th>郵便番号</th><td>***********</td></tr> 14 <tr><th>住所</th><td>***********</td></tr> 15 <tr><th>電話番号</th><td>***********</td></tr> 16 <tr><th>担当様</th><td>***********</td></tr> 17 </tbody> 18</table> 19<table class="info"> 20 <tbody> 21 <tr><th>名前</th><td>***********</td></tr> 22 <tr><th>郵便番号</th><td>***********</td></tr> 23 <tr><th>住所</th><td>***********</td></tr> 24 <tr><th>電話番号</th><td>***********</td></tr> 25 <tr><th>担当様</th><td>***********</td></tr> 26 </tbody> 27</table>
###該当のソースコード
ruby
1driver.find_elements(:class_name => "info").each do |i| 2 p i.driver.find_element(:xpath => "//th[text()='名前']/following-sibling::td") 3 p i.driver.find_element(:xpath => "//th[text()='郵便番号']/following-sibling::td") 4 p i.driver.find_element(:xpath => "//th[text()='住所']/following-sibling::td") 5 p i.driver.find_element(:xpath => "//th[text()='電話番号']/following-sibling::td") 6 p i.driver.find_element(:xpath => "//th[text()='担当様']/following-sibling::td") 7end
ruby
1doc = Nokogiri::HTML driver.page_source 2doc.xpath("//*[@class ='info']").each do |i| 3 p i.xpath("//*[text()='名前']/following-sibling::td").inner_text 4 p i.xpath("//*[text()='郵便番号']/following-sibling::td").inner_text 5 p i.xpath("//*[text()='住所']/following-sibling::td").inner_text 6 p i.xpath("//*[text()='電話番号']/following-sibling::td").inner_text 7 p i.xpath("//*[text()='担当様']/following-sibling::td").inner_text 8end
###試したこと
1つ目のコードはseleniumを使用しています。出力はエラーになり「Unable to find element with xpath」と表示されます。
2つ目のコードはNokogiriとseleniumを使用していますが、出力は空になります。
each文を使用するとこのようなエラーによく陥ります。
どなたかアドバイスお願い致します。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。