需匹配双XPath条件的页面首条记录查询问题及修正求助
问题
需要查找页面中同时满足以下两个条件的首条记录:
- 条件一:发货地为英国,对应HTML片段:
<span class="mplabel">Ships From:</span>United Kingdom</li>
- 条件二:包含文本片段"handled by a previous owner who took good",对应HTML片段:
<span class="tooltip-inner xh-highlight"> Will show some signs that it was played and otherwise handled by a previous owner who took good care of it. </span>
尝试过的XPath无法正确匹配(例如在目标页面错误匹配比利时卖家):
(//li[contains(text(), 'United Kingdom')]/preceding::span[contains(text(), 'took good care')][1]/following::td[@class='seller_info']/ul/li[4]/strong/a)[1]
解决方案
之前的XPath错误在于没有限定两个条件属于同一条商品记录,导致跨节点匹配。以下是正确的表达式:
匹配首条符合条件的商品记录(<tr>节点)
//tr[ .//span[@class='tooltip-inner' and contains(text(), 'handled by a previous owner who took good')] and .//li[span[@class='mplabel' and text()='Ships From:'] and contains(text(), 'United Kingdom')] ][1]
提取该记录的卖家链接(若需此目标)
(//tr[ .//span[@class='tooltip-inner' and contains(text(), 'handled by a previous owner who took good')] and .//li[span[@class='mplabel' and text()='Ships From:'] and contains(text(), 'United Kingdom')] ]/td[@class='seller_info']//strong/a)[1]
核心逻辑
- 以
<tr>作为匹配的根容器,确保两个条件都属于同一条商品条目,避免跨记录误匹配。 - 条件一精准定位:匹配当前
<tr>下带有Ships From:标签且文本包含United Kingdom的<li>。 - 条件二精准定位:匹配当前
<tr>下class为tooltip-inner且包含指定文本片段的<span>。 [1]筛选出符合条件的首条结果。
内容的提问来源于stack exchange,提问作者Rich Stevens
相关产品推荐
相关产品推荐

