【问题标题】:XPath How to compute 2 nodes and limit results for oneXPath 如何计算 2 个节点并限制一个节点的结果
【发布时间】:2021-12-18 14:15:18
【问题描述】:

什么是正确的语法:

//footer//a | (//a[not(//footer)] and position() <=200)

如果存在则仅使用 //footer,如果不存在,则查找所有不在 //footer 中的 //a 并将其限制为 200

【问题讨论】:

    标签: python python-3.x web-scraping xpath scrapy


    【解决方案1】:

    你真的很亲密。 OR 运算符已经处理了您的情况 - 如果页脚下面不包含 &lt;a&gt; 节点,则将捕获第二个 OR 语句:

    使用pythonparsel(scrapy 的 html 解析器)。

    >>> foo = Selector("<footer><a>text</a></footer>")
    >>> bar = Selector("<div><a>text</a><a>text2</a><a>text3</a><a>text4</a></div>")
    >>> foo.xpath("//footer//a | //a[position()<=2]").get()
    '<a>text</a>'
    
    >>> bar.xpath("//footer//a | //a[position()<=2]").extract()
    ['<a>text</a>', '<a>text2</a>']
    

    注意:为简洁起见,我使用了2 而不是200

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2012-12-03
      相关资源
      最近更新 更多