【问题标题】:How to select elements when there is a space in an HTML classHTML类中有空格时如何选择元素
【发布时间】:2013-12-02 12:10:38
【问题描述】:
如何使用 CSS 选择器来获得下面的“这是我需要的文本”行?
我不知道如何处理表格类中的空格。
<table class="some name">
<thead>
</thead>
<tbody>
<tr>
<td style="text-align:center;">50</td>
<td style="text-align:left;"><a href="/thing" title="thing">This is the text I need</a></td>
【问题讨论】:
标签:
ruby
css-selectors
web-scraping
nokogiri
【解决方案1】:
如果类属性值中有空格,则表示该元素应用了多个类。要定位具有多个类的元素,css 选择器只是类的链。通常,表单如下所示:
element.class1.class2
因此,假设链接是表中第一个具有“some”和“name”类的链接,您可以这样做:
require 'nokogiri'
html = %Q{
<table class="some name">
<thead>
</thead>
<tbody>
<tr>
<td style="text-align:center;">50</td>
<td style="text-align:left;"><a href="/thing" title="thing">This is the text I need</a></td>
</tr>
</tbody>
</table>
}
doc = Nokogiri::XML(html)
# Assuming you need both classes to uniquely identify the table
p doc.at_css('table.some.name a').text
#=> "This is the text I need"
# Note that you do not need to use both classes if one of them is unique
p doc.at_css('table.name a').text
#=> "This is the text I need"