[英]nokogiri multiple css classes
How is it possible to select an html element that have two classes? 如何选择具有两个类的html元素?
For example, how to select the element <p>
bellow in an HTML document (given that it has two css classes) class='class1 class2'
. 例如,如何在HTML文档中选择下面的元素<p>
(假设它具有两个CSS类) class='class1 class2'
。
I tried to use the following: 我尝试使用以下内容:
doc.xpath("//p[@class~='class1 class2']")
doc.xpath("//p[@class~='class1']|[@class~='class2']")
doc.xpath("//p[@class~='class1',@class~='class2']")
doc.xpath("//p[contains(concat(' ', @class, ' '), ' class1 ') && contains(concat(' ',@class, ' '), ' class2 ')]")
but without success. 但没有成功。
Thanks in advance 提前致谢
Finally I found the RIGHT way to search multiple css classes with nokogiri (libxml) : 最后,我找到了使用nokogiri(libxml)搜索多个CSS类的正确方法:
doc.xpath('//p[contains(@class, "class1") and contains(@class, "class2")]')
It's not perfect, because if <p>
contains classes such as class10
and class20
the element will be selected, but for now it's enough for what I need. 这不是完美的,因为如果<p>
包含class10
和class20
这样的类,则将选择该元素,但就目前而言,它足以满足我的需要。 If you have more suggestions they are welcome! 如果您有更多建议,欢迎您!
Here is a better solution to this problem using css only : 这是仅使用css的更好解决方案:
doc.css('p.class1.class2')
Thanks to Aaron Patterson :-) 感谢Aaron Patterson :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.