Here是获取唯一值的一种方法。如果我想得到唯一的属性,它就无效了。例如:
<a href = '11111'>sometext</a>
<a href = '11121'>sometext2</a>
<a href = '11111'>sometext3</a>我想要一个独特的裁判。受XPath1.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() )。此外,如果链接的父级相同,则我的解决方案不起作用。
发布于 2018-10-19 09:34:45
你可以提取所有的萤火虫,然后找出唯一的:
all_hrefs = page_src.xpath('//a/@href')
unique_hrefs = list(set(all_hrefs))https://stackoverflow.com/questions/52836869
复制相似问题