keisei_1092 keisei_1092 - 3 months ago 11
Ruby Question

How to scrape data using Nokogiri from elements having two 'data-' attributes

I want to scrape data using Nokogiri from such HTML:

<td data-bar="hoge" data-date="2000-01-01" class="modals"></td>
<td data-bar="fuga" data-date="2000-01-02" class="modals"></td>


I wrote:

element = page.css("td[data-bar='hoge'][data-date='2000-01-01']")


but
element.length
returns
0
.

How to distinguish elements having two
data-
attributes? Any helps would be thankful.

Answer

Try using XPath selectors instead. This worked for me:

element = page.xpath "//td[@data-bar='hoge'][@data-date='2000-01-01']"

In this example, the '//' portion signifies the root of the DOM, so you'll still need to write the XPath to the element you are searching for.

Here's the documentation for XPath: https://www.w3.org/TR/xpath/