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

【已解决】xpath中以正则方式去选择和查找属性

XPath crifan 6324浏览 0评论

【问题】

C#中,用HtmlAgilityPack去解析html,其中用xpath去查找对应的内容。

对于:

<div id="atfResults" class="list results twister">
<div id="result_0" class="result firstRow product celwidget" name="B00CE18P0K">
<div id="result_1" class="result product celwidget" name="B00CL68QVQ">
<div id="result_2" class="result lastRow product celwidget" name="B008Y7N7JW">

<div id="btfResults" class="list results twister">
<div id="result_3" class="result product celwidget" name="B008XKSW7M">

希望写出xpath中的正则的方式去匹配出来。

就类似于:

//div[@id=’result_\d+’ and @class=’result.+’ and @name=’\w+’]

的形式的。

【解决过程】

1.参考:

Can I use a Regex in an XPath expression?

的值,Xpath 1.0,不支持正则。

参考其写法,用:

HtmlNodeCollection resultItemNodeList =
                htmlDoc.DocumentNode.SelectNodes("//div[starts-with(@id, 'result_') and starts-with(@class, 'result ') and @name]");

结果找不到。

2.先试试:

HtmlNodeCollection resultItemNodeList = htmlDoc.DocumentNode.SelectNodes("//div[@id and @class and @name]");

然后是可以找到我要的内容,但是却是不带正则的写法,而且容易有误判。

3.参考:

http://www.w3school.com.cn/xpath/xpath_functions.asp

看到解释:

fn:contains(string1,string2)

如果 string1 包含 string2,则返回 true,否则返回 false。

例子:contains(‘XML’,’XM’)

结果:true

fn:starts-with(string1,string2)

如果 string1 以 string2 开始,则返回 true,否则返回 false。

例子:starts-with(‘XML’,’X’)

结果:true

fn:ends-with(string1,string2)

如果 string1 以 string2 结尾,则返回 true,否则返回 false。

例子:ends-with(‘XML’,’X’)

结果:false

然后继续去试试。

4.结果后来的测试结果表明,上述的写法,是可以的。

只不过是,由于所访问的amazon的url后得到的html有问题,导致有时候可以用xpath查找到结果,有时候没有结果。

最后就是用上面的那个代码:

resultItemNodeList = htmlDoc.DocumentNode.SelectNodes("//div[starts-with(@id, 'result_') and starts-with(@class, 'result ') and @name]");

实现的正则查找的。

 

【总结】

1. xpath中实现正则查找的话:

  • xpath 1.0:不支持正则,但是可以利用到xpath内置所支持的各种函数,间接实现类似的效果:
    • 用:
    • //div[starts-with(@id, ‘result_’) and starts-with(@class, ‘result ‘) and @name]
    • 匹配到:
    • <div id="result_0" class="result firstRow product celwidget" name="B00CE18P0K">

      <div id="result_1" class="result product celwidget" name="B00CL68QVQ">

      <div id="result_2" class="result lastRow product celwidget" name="B008Y7N7JW">

  • xpath 2.0:本身就支持正则,对应的一些函数:

 

2.更多解释详见:

Can I use a Regex in an XPath expression?

 

3.更多内置函数,参见:

http://www.w3school.com.cn/xpath/xpath_functions.asp

转载请注明:在路上 » 【已解决】xpath中以正则方式去选择和查找属性

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.170 seconds, using 22.05MB memory