Skip to content Skip to sidebar Skip to footer

Locating Nearest Button Selenium Python

I am trying to click the 'Delete Comment' button after finding the comment that contains a specific hashtag, husky, which is a hyperlink. Since there are multiple 'Delete Comment'

Solution 1:

You can use one of xpath below.

Explanation: find a with "#hasky" text, get first parent li with "menuitem" role and get child button (with "Delete Comment" title attribute):

//a[.='#husky']/ancestor::li[@role='menuitem'][1]//button

//a[.='#husky']/ancestor::li[@role='menuitem'][1]//button[@title='Delete Comment']

//a[contains(@href, "/explore/tags/husky/")]/ancestor::li[@role='menuitem'][1]//button

//li[@role='menuitem' and .//a[.='#husky']]//button[@title='Delete Comment']

Solution 2:

Something simple like

//a[.='#husky']//following::button[@title='Delete Comment'][1]

should work just fine. If it were me, I would wrap this in a method and pass in the link text to delete the appropriate comment. You can then take the link text and put it into the locator in the place of #husky.

def delete_comment(comment)
    driver.find_element_by_xpath(f"//a[.='{comment}']//following::button[@title='Delete Comment'][1]").click()

Post a Comment for "Locating Nearest Button Selenium Python"