如何用XPath提取表格指定列的单元格数据?
问题:用XPath提取表格指定列(表头显示"6"的列)单元格数据
需要提取目标表格中表头显示"6"的列对应的所有单元格数据,部分单元格无内容,尝试过的XPath表达式无效,计划在Octoparse中使用XPath完成提取。
目标表格代码:
<table class="table table-responsive table-striped" style="color:#fff; "> <thead> <tr> <th scope="col"><div style="width:100%;">#</div></th> <th scope="col" sort="outfit_name"><div style="width:100%;min-width:150px" class="btn btn-primary" sort="name" onclick="reorder('1')">1</div></th> <th scope="col" sort="price"><div style="width:100%;" class="btn btn-primary" sort="rarity" onclick="reorder('rarity')">2</div></th> <th scope="col" sort="text"><div style="width:100%;min-width:50px" class="btn btn-primary" sort="outfitType" onclick="reorder('2')">3</div></th> <th scope="col" sort="text"><div style="width:100%;min-width:50px" class="btn btn-primary" sort="craftable" onclick="reorder('3')">4</div></th> <th scope="col" sort="text"><div style="width:100%;min-width:50px" class="btn btn-primary" sort="locationText" onclick="reorder('4')">5</div></th> <th scope="col" sort="instructions"><div style="width:100%;" class="btn btn-primary" sort="vendorText" onclick="reorder('5')">6</div></th> <th scope="col" sort="outfit_class"><div style="width:100%;" class="btn btn-primary" sort="themeText" onclick="reorder('6')">7</div></th> </tr> </thead> <tbody> <tr> <th scope="row" style="font-size: 14px; vertical-align: middle;">1</th> <td style="font-size: 13px; vertical-align: middle;">info here</td> <td style="font-size: 13px; text-align:center; vertical-align: middle;">info here</td> <td style="font-size: 13px; text-align:center; vertical-align: middle;">info here</td> <td style="font-size: 13px; text-align:center; vertical-align: middle;"> info here </td> <td style="vertical-align: middle;"></td> <td style="vertical-align: middle;"><div style="width:85px;" onclick="load_vendor(this)" context="<p>data here</p>" outfit="Name Here" class="btn btn-primary"> 🛒️</div></td> <td style="vertical-align: middle;"><div style="width:93px;" onclick="load_theme(this)" context="<p>data here</p>" outfit="Name Here" class="btn btn-primary"> ℹ️ </div></td> </tr> </tbody> </table>
尝试过的无效XPath:
//td[position()<=(count(//tr/th[.='6']/preceding-sibling::*)+1)]
可行解决方案
思路1:按表头文本动态定位列位置
通过表头中显示"6"的<th>元素确定列的位置,再提取tbody中对应位置的单元格,适合列位置可能变化的场景:
//tbody/tr/*[position() = count(//thead/tr/th[div/text()='6']/preceding-sibling::*) + 1]
思路2:直接固定位置提取(列位置固定时)
如果表头列位置不会变动,直接选择tbody每行的第7个元素(对应表头显示"6"的列),或直接选择第6个<td>:
//tbody/tr/*[7]
或
//tbody/tr/td[6]
思路3:利用表头语义化属性定位(更可靠)
表头中显示"6"的<th>带有sort="instructions"属性,通过该属性定位列位置,避免文本变动影响:
//tbody/tr/*[position() = count(//thead/tr/th[@sort='instructions']/preceding-sibling::*) + 1]
提取单元格内的属性(如需)
如果需要提取单元格内按钮的context或outfit属性,可使用以下XPath:
//tbody/tr/td[6]/div/@context
或
//tbody/tr/td[6]/div/@outfit
在Octoparse中使用时,将对应XPath填入数据提取规则的XPath输入框,根据需求选择提取文本、HTML或属性值即可。
内容的提问来源于stack exchange,提问作者Eric K.
相关产品推荐
相关产品推荐

