find_elements_by_xpath that do not contains 3 times a specific string

Viewed 50

I have used this code but I want to remove those links where it appears the string 'vs' three times in the link, it only has to appear one time:

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"))

enter image description here

Update: I have realised that some of my code is not working as I expected, I used the code : [not(@href = following::a/@href)] to remove repeated href but there is still one href that is repeated. Any help is welcome!

2 Answers

Try this:

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"))

To get link with only one occurrence of "_vs_" in @href you can extend your XPath with predicate

[not(contains(substring-after(@href, "_vs_"), "_vs_"))]

Your final XPath will be

"//a[contains(@href, '/president/us/general_election') and not(contains(substring-after(@href, "_vs_"), "_vs_")) and not(@href = following::a/@href)]"
Related