xpath:如何编写条件xpath?

时间:2013-04-23 12:40:32

标签: python xpath lxml

我试图从以下两页中提取价格信息:

http://jujumarts.com/mobiles-accessories-smartphones-wildfire-sdarkgrey-p-551.html http://jujumarts.com/computers-accessories-transcend-500gb-portable-storejet-25d2-p-2616.html

xpath1 = //span[@class='productSpecialPrice']//text()
xpath2 = //div[@class='proDetPrice']//text()

截至目前,我编写了python代码,如果成功则返回xpath1的结果,否则执行第二个。我觉得有可能单独在xpath中实现这个逻辑,有人可以告诉我怎么做?

1 个答案:

答案 0 :(得分:4)

使用|表示union

xpath3 = "//span[@class='productSpecialPrice']//text()|//div[@class='proDetPrice']//text()"

这并不是您要求的,但我认为它可以纳入可行的解决方案中。


来自the XPath (version 1.0) specs

  

| operator计算其操作数的并集,必须是   节点集。


例如,

import lxml.html as LH

urls = [
    'http://jujumarts.com/mobiles-accessories-smartphones-wildfire-sdarkgrey-p-551.html',
    'http://jujumarts.com/computers-accessories-transcend-500gb-portable-storejet-25d2-p-2616.html'
    ]

xpaths = [
    "//span[@class='productSpecialPrice']//text()",
    "//div[@class='proDetPrice']//text()",
    "//span[@class='productSpecialPrice']//text()|//div[@class='proDetPrice']//text()"
    ]
for url in urls:
    doc = LH.parse(url)
    for xpath in xpaths:
        print(doc.xpath(xpath))
    print

产量

['Rs.11,800.00']
['Rs.13,299.00', 'Rs.11,800.00']
['Rs.13,299.00', 'Rs.11,800.00']

[]
['Rs.7,000.00']
['Rs.7,000.00']

获取所需信息的另一种方法是

"//*[@class='productSpecialPrice' or @class='proDetPrice']//text()"