How to get a HTML table row with Capybara

后端 未结 1 433
终归单人心
终归单人心 2020-12-30 11:55

I am trying to scan rows in a HTML table using partial href xpath and perform further tests with that row\'s other column values.

  
相关标签:
1条回答
  • 2020-12-30 12:22

    I think you are looking to do:

    page.all('#blah tr').each do |tr|
      next unless tr.has_selector?('a[href*="HONDA"]')
    
      # Do stuff with trs that meet the href requirement
      puts tr.text
    end
    #=> link 29 33 485 45.2934,00 EUR
    #=> link 22 93 485 38.336.934,123 EUR
    

    This basically says to:

    1. Find all trs in the element with id 'blah'
    2. Iterate through each of the trs
    3. If the tr does not have a link that has a href containing HONDA, ignore it
    4. Otherwise, output the text of the row (that matches the criteria). You could do whatever you need with the tr here.

    You could also use xpath to collapse the above into a single statement. However, I do not think it is as readable:

    page.all(:xpath, '//div[@id="blah"]//tr[.//a[contains(@href, "HONDA")]]').each do |tr|
      # Do stuff with trs that meet the href requirement
      puts tr.text
    end
    #=> link 29 33 485 45.2934,00 EUR
    #=> link 22 93 485 38.336.934,123 EUR
    

    Here is an example of how to inspect each matching row's link url and column values:

    page.all('#blah tr').each do |tr|
      next unless tr.has_selector?('a[href*="HONDA"]')
    
      # Do stuff with trs that meet the href requirement
      href = tr.find('a')['href']
      column_value_1 = tr.all('td')[1].text
      column_value_2 = tr.all('td')[2].text
    
      puts href, column_value_1, column_value_2
    end
    #=> file:///C:/Scripts/Misc/Programming/Capybara/afile?key=HONDA
    #=> 29 33 485
    #=> 45.2934,00 EUR
    #=> file:///C:/Scripts/Misc/Programming/Capybara/afile?key=HONDA
    #=> 22 93 485
    #=> 38.336.934,123 EUR
    
    0 讨论(0)
提交回复
热议问题