【问题标题】:Recursive function with selenium带有硒的递归函数
【发布时间】:2020-12-06 14:15:33
【问题描述】:

我正在尝试在 python 中使用 selenium 进行一些网络自动化,如果我的脚本遇到任何错误,我希望整个过程再次重新启动(无限循环) 所以基本上我尝试使用递归函数并在每次发生错误时调用它,它看起来像这样:

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

def my_func():
    try :
        driver.get("https://mywebsite.com")
        .
        .
        .
    except Exception as E : 
        print(str(E)) #printing the exception message
        driver.quit() #quitting from the current tab
        my_func() #recalling the function again 

my_func()

    

第一次一切正常并且发生错误时(因为网站切换到另一个页面)它会打印此异常:Message: element not interactable 这是完全正常的,但在第二次迭代中我得到了这个:

HTTPConnectionPool(host='127.0.0.1', port=59887): Max retries exceeded with url: /session/6d23ab3406dbef8f6581c4c7652d2633/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000019D2BA3CC10>: Failed to establish a new connection: `[WinError 10061] No connection could be made because the target machine actively refused it'))

那么有什么方法可以修复这个错误或这个脚本的其他更好的解决方案吗?

【问题讨论】:

  • 这只是意味着你的发送请求太快了添加一个time.sleep。

标签: python selenium selenium-webdriver exception web-scraping


【解决方案1】:

我想,信息:

No connection could be made because the target machine actively refused it

这可能是由目标 URL 引起的安全问题。尝试通过其他连接(例如移动热点)连接到互联网。

【讨论】:

    【解决方案2】:

    我发现我必须在每次迭代时创建一个新的驱动程序,我还在调用函数之前添加了一个 time.sleep,以防请求发送得太快:

    def my_func():
        try :
            PATH = "C:\Program Files (x86)\chromedriver.exe"
            driver = webdriver.Chrome(PATH)
            driver.get("https://mywebsite.com")
            .
            .
            .
        except Exception as E : 
            print(str(E)) #printing the exception message
            driver.quit() #quitting from the current tab
            time.sleep(5)
            my_func() #recalling the function again 
    
    my_func()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 2019-01-19
      • 2013-08-30
      • 2015-12-05
      • 2017-12-12
      • 2017-03-25
      相关资源
      最近更新 更多