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" buttons, I think the best way is to just find the comment that has the hashtag, and then click the nearest button, but I could be wrong there.
In the picture, I want to click the button highlighted below the hashtag, not below:
So far, I have
self.browser.find_element_by_xpath('//a[@href="/explore/tags/husky/"]')
Which successfully locates the tag, but I am stumped after that.
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']
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()