使用 python 和 selenium 删除我在 reddit 中的评论

Use python and selenium to delete my comments in reddit

我正在尝试编写一个脚本来删除我在 Reddit 个人资料上的所有评论。

所以我目前正在使用 Selenium 登录并尝试删除我的评论,但是当我的脚本在我的评论上按删除键后它变为 "Are you sure Yes/No" 那么它无法通过 Xpath 找到 "Yes" 元素。以下代码引发错误:

raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace:

我的代码如下:

    del_button = driver.find_element_by_xpath("//*[contains(@id,'thing_"+delete_type+"')]//div[2]/ul/li[7]/form/span[1]/a")
    del_button.click()        
    time.sleep(3)
    yes_button = driver.find_element_by_xpath("//*[contains(@id,'thing_"+delete_type+"')]//div[2]/ul/li[7]/form/span[1]//a[1]")
    yes_button.click()
    time.sleep(3)      

由于页面上可能有多个具有相同属性的隐藏元素,您可能需要使用 index 来点击确切的元素:

driver.find_elements_by_xpath('//a[@class="yes"]')‌​[N].clic‌​k() # N is the index of target link

如果你不能定义准确的索引,你可以使用下面的代码:

from selenium.common.exceptions import ElementNotVisibleException

for link in driver.find_elements_by_xpath('//a[@class="yes"]')‌:
    try:
        link.click()
        break
    except ElementNotVisibleException:
        pass