最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中的Xpath选择多个属性

C# crifan 67352浏览 0评论

【问题】

对于html:

<a href="/search?q=weight+loss+site:.edu+inurl:blog+%22post+a+comment%22+-%22you+must+be+logged+in%22&amp;newwindow=1&amp;safe=strict&amp;ei=XZp2UczlE8nYigeK5IHgCg&amp;start=10&amp;sa=N" class="pn" id="pnnext" style="text-decoration:none;text-align:left"><span class="csb gbil ch" style="background-position:-96px 0;width:71px"></span><span style="display:block;margin-left:53px;text-decoration:underline">Next</span></a>

想要使用xpath去选择此a,对于选择单个属性,可以使用的xpath是:

//a[@id='pnnext']

//a[@class='pn']

但是想要同时选择这两个属性,就不知道如何写了。

【解决过程】

1.参考:

XPATH – selection based on multiple attribute values

得到对应的写法:

//a[@id='pnnext' and class='pn']

所以去用:

HtmlNode nextHtmlNode = rootHtmlNode.SelectSingleNode("//a[@id='pnnext' and class='pn']");

结果找不到。

其中,确定html中是有:

<a href="/search?q=weight+loss+site:.edu+inurl:blog+%22post+a+comment%22+-%22you+must+be+logged+in%22&amp;newwindow=1&amp;safe=strict&amp;ei=yU13UZy6GsiZiAfqmYCQCA&amp;start=10&amp;sa=N" class="pn" id="pnnext" style="text-decoration:none;text-align:left"><span class="csb gbil ch" style="background-position:-96px 0;width:71px"></span><span style="display:block;margin-left:53px;text-decoration:underline"><b>下一頁</b></span></a>

的。

很是诡异。

 

2.换成:

HtmlNode nextHtmlNode = rootHtmlNode.SelectSingleNode("//a[@id='pnnext' and @class='pn']");

试试,然后就可以了。

 

【总结】

Xpath中,要选择多个属性的写法是:

//a[@id='pnnext' and @class='pn']

就可以匹配到:

<a … class="pn" id="pnnext" …">xxx</a>

了。

转载请注明:在路上 » 【已解决】C#中的Xpath选择多个属性

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.183 seconds, using 22.04MB memory