【问题标题】:python lxml xpath 1.0 : unique values for element's attributepython lxml xpath 1.0:元素属性的唯一值
【发布时间】:2018-10-16 13:41:07
【问题描述】:

Here 是一种获取唯一值的方法。如果我想获得唯一属性,它不起作用。 例如:

<a href = '11111'>sometext</a>
<a href = '11121'>sometext2</a>
<a href = '11111'>sometext3</a>

我想获得独特的href。使用 xpath 1.0 限制

page_src.xpath( '(//a[not(.=preceding::a)] )')
page_src.xpath( '//a/@href[not(.=preceding::a/@href)]' )

返回重复项。 unique-values缺席能否解决这个噩梦?

UPD:这不是我想要的函数的解决方案,但我编写了 python 函数,它迭代父元素并检查是否添加父标记过滤器链接到所需的计数。

这是我的例子:

_x_item = (
    '//a[starts-with(@href, "%s")'
    'and (not(@href="%s"))'
    'and (not (starts-with(@href, "%s"))) ]'
    %(param1, param1, param2 ))

#rm double links
neededLinks = list(map(lambda vasa: vasa.get('href'), page_src.xpath(_x_item)))
if len(neededLinks)!=len(list(set(neededLinks))):
    uniqLength = len(list(set(neededLinks)))
    breakFlag = False
    for linkk in neededLinks:
        if neededLinks.count(linkk)>1:
            dupLinks = page_src.xpath('//a[@href="%s"]'%(linkk))
            dupLinkParents = list(map(lambda vasa: vasa.getparent(), dupLinks))
            for dupParent in dupLinkParents:
                tempLinks = page_src.xpath(_x_item.replace('//','//%s/'%(dupParent.tag)))
                tempLinks = list(map(lambda vasa: vasa.get('href'), tempLinks))
                if len(tempLinks)==len(set(neededLinks)):
                    breakFlag = True
                    _x_item = _x_item.replace('//','//%s/'%(dupParent.tag))
                    break
            if breakFlag:
                break

如果重复链接具有不同的父级,但 @href 值相同,这将起作用。

因此,我将添加 parent.tag 前缀,例如 //div/my_prev_x_item

另外,使用 python,我可以将结果更新为 //div[@key1="val1" and @key2="val2"]/my_prev_x_item,迭代 dupParent.items()。但这只有在项目不在同一个父对象中时才有效。

结果我只需要 x_path_expression,所以我不能只使用 list(set(myItems))

如果存在,我想要更简单的解决方案(例如 unique-values() )。另外,如果链接的父级相同,我的解决方案将不起作用。

【问题讨论】:

  • 你使用的是什么版本的 lxml?您的第二个 xpath 在 4.2.1 版中对我来说很好。您可以改用//a[not(@href=preceding::a/@href)]/@href,但就像我说的//a/@href[not(.=preceding::a/@href)] 对我来说效果很好。
  • 1.0(python lxml.xpath函数)

标签: python-3.x lxml xpath-1.0


【解决方案1】:

您可以提取所有href,然后找到唯一的:

all_hrefs = page_src.xpath('//a/@href')
unique_hrefs = list(set(all_hrefs))

【讨论】:

  • 我只需要 x-path 解决方案。使用 python 很简单,我知道
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2016-02-11
  • 1970-01-01
  • 2012-12-24
相关资源
最近更新 更多