【问题标题】:scrapy and xpath function 'matches' syntaxscrapy 和 xpath 函数“匹配”语法
【发布时间】:2014-01-04 11:52:14
【问题描述】:

我正在运行scrapy 0.20.2。

$ scrapy shell "http://newyork.craigslist.org/ata/"

我想将所有指向广告页面的链接列表与 index.html 分开

$ sel.xpath('//a[contains(@href,html)]')
... 
<Selector xpath='//a[contains(@href,"html")]' data=u'<a href="/mnh/atq/4243973984.html">Wicke'>,
<Selector xpath='//a[contains(@href,"html")]' data=u'<a href="/mnh/atd/4257230057.html" class'>,
<Selector xpath='//a[contains(@href,"html")]' data=u'<a href="/mnh/atd/4257230057.html">Recla'>,
<Selector xpath='//a[contains(@href,"html")]' data=u'<a href="/ata/index100.html" class="butt'>]

我想使用 XPath 匹配函数来匹配正则表达式 [0-9]+.html 形式的链接。

$ sel.xpath('//a[matches(@href,"[0-9]+.html")]')
...
ValueError: Invalid XPath: //a[matches(@href,"[0-9]+.html")]

怎么了?谢谢。

【问题讨论】:

    标签: regex xpath scrapy


    【解决方案1】:

    matches 是一个 XPath 2.0 函数,scrapy 只支持 XPath 1.0(它没有内置任何正则表达式支持)。您必须使用 scrapy 选择器提取所有链接,然后在 Python 级别而不是在 XPath 中进行正则表达式过滤。

    【讨论】:

      【解决方案2】:

      对于这个特殊用例,有一个使用 translate(...) 的 XPath 1.0 解决方法:

      //a[
        translate(substring-before(@href, '.html'), '0123456789', '') = ''
        and @href != '.html'
        and substring-after(@href, '.html') = '']
      

      translate(...) 调用会删除名称部分中 .html 扩展名之前的所有数字。第二行检查确保 .html 被排除在外(点前没有任何内容),最后一行检查确保 .html 实际上是文件扩展名。

      【讨论】:

        猜你喜欢
        • 2010-10-18
        • 1970-01-01
        • 2022-06-16
        • 1970-01-01
        • 2023-03-23
        • 2011-08-04
        • 2010-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多