【问题标题】:How can I get the response of a click event to handle exception on Selenium with Python?如何获得单击事件的响应以使用 Python 处理 Selenium 上的异常?
【发布时间】:2020-09-15 12:18:26
【问题描述】:

我正在使用 Selenium 对 Instagram 上的帖子自动执行一些评论操作。流程如下:脚本等待textarea可以点击,然后点击它,写评论,等待“发布”按钮可以点击,然后点击它。但是,即使我限制为很少的 cmets(20 cmets/小时)并在两者之间留出足够的时间,但有时所有内容都可以点击,但评论不会通过,并且底部会显示一个小横幅点击“发布”后页面显示“无法发表评论”,然后文本区域不再可点击。
这是我的一段代码:

...
try:
    comment_post = WebDriverWait(self.webdriver, 10).until(
                   EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']")))
    if comment_post.text == "Post":
        comment_post.click()
        sleep(random.randint(2,5))
        return
...

问题是即使没有发布评论,try 语句也会通过,因为.click() 操作可用。如何获得点击的响应('无法发表评论'),以便我可以引发异常并让应用程序等待它再次可用或刷新页面或其他什么?

【问题讨论】:

    标签: python selenium bots instagram


    【解决方案1】:

    点击后您将不得不等待并搜索横幅是否存在。如果您找到横幅,则引发异常。

    类似这样的:

    comment_post.click()
    try:
        nocommentbanner = WebDriverWait(self.webdriver, 10).until(
                   EC.visibility_of_element_located((By.SOMEHOW, someway)))
        # banner found
        # comment fail
        # maybe raise CommentFailed()
    except TimeoutException:
        # banner not found
        # comment success
        # perhaps do nothing
    

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多