Searching for two CSS Selectors with an OR relationship

9 views
Skip to first unread message

wi...@twentypine.com

unread,
May 15, 2017, 3:44:38 AM5/15/17
to nokogiri-talk
I'm working through some HTML with CSS classes and there are two classes I want to be processed by my do loop. I want it to look for everything with the class "info-block" and the class "title_date" I can't figure out how to use OR logic with the search function. Is it possible?

page.search('.info-block', '.title_date').map do |c|
   
# do stuff with c
end

Help appreciated.

Walter Lee Davis

unread,
May 15, 2017, 9:26:25 AM5/15/17
to nokogi...@googlegroups.com
You are really really close here, but you need to think in CSS (or XPath, which it will be converted to, but which I don't know as well as CSS):

page.css('.info-block, .title_date').each do |c|
...

The argument to the #css method is any CSS selector, just as you may define it in a stylesheet.

There is one tiny wrinkle to this, which may impact your work inside the loop: the items will be returned to your iterator as [list of all items that match .info-block], followed by [list of all items that match .title_date]. If the transformation you want to make within the block relies on the order of these items matching their order as found by scanning the entire document from top to bottom, then you may need to do something more brute-force, like selecting on div, then rejecting the items that don't have the classes you are interested in.

Walter
> --
> You received this message because you are subscribed to the Google Groups "nokogiri-talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to nokogiri-tal...@googlegroups.com.
> To post to this group, send email to nokogi...@googlegroups.com.
> Visit this group at https://groups.google.com/group/nokogiri-talk.
> For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages