Python 通过xpath查找不包含3倍特定字符串的元素
我使用了此代码,但我想删除链接中出现字符串“vs”三次的链接,它只需出现一次:Python 通过xpath查找不包含3倍特定字符串的元素,python,selenium,xpath,Python,Selenium,Xpath,我使用了此代码,但我想删除链接中出现字符串“vs”三次的链接,它只需出现一次: elems = driver.find_elements_by_xpath("//a[contains(@href, '/president/us/general_election')][not(@href = following::a/@href)]") for elem in elems: print(elem.get_attribute("href")) 更新
elems = driver.find_elements_by_xpath("//a[contains(@href, '/president/us/general_election')][not(@href = following::a/@href)]")
for elem in elems:
print(elem.get_attribute("href"))
更新:
我意识到我的一些代码并没有像我预期的那样工作,我使用了代码:[不是(@href=following::a/@href)]
来删除重复的href,但仍然有一个href是重复的。欢迎任何帮助 试试这个:
elems = driver.find_elements_by_xpath("//a[contains(@href, '/president/us/general_election')][not(@href = following::a/@href)]")
for elem in elems:
if elem.get_attribute("href").count("vs") == 1: print(elem.get_attribute("href"))
要在
@href
中仅获取一次出现的“\u vs_u”
链接,可以使用谓词扩展XPath
[not(contains(substring-after(@href, "_vs_"), "_vs_"))]
您的最终XPath将是
"//a[contains(@href, '/president/us/general_election') and not(contains(substring-after(@href, "_vs_"), "_vs_")) and not(@href = following::a/@href)]"