在用selenium进行自动化模拟的时候,为了防止反爬,我们需要在自动化浏览器中加入代理ip,以防止自动化浏览器突然停止不前,虽然在网上了解到用`driver.set_page_load_timeout(time)`这个等待页面加载完成,但偶尔间,超时后也没有进行下一步运行。今天就介绍了一下,用装饰器和封装工具来做一个小小的实际运用。
装饰器函数
满足装饰器函数的前提条件是:
1. 必须有一个内嵌函数
2. 内嵌函数必须引用外部函数中的变量
3. 外部函数返回值必须是内嵌函数
那么在代码里,需要这么写
def check(func):
    def wraper(*args):
        ago_pid = func(*args)
        print(ago_pid)
        time.sleep(3)
        all_pid = psutil.process_iter()
        now_pid = func(all_pid)
        print(now_pid)
        if ago_pid == now_pid:
            os.system('taskkill /f /im %s' % 'chrome.exe')
            os.system('taskkill /f /im %s' % 'chromedriver.exe')
    return wraper监控程序中
@check
def jiankong(all_pid):
    while True:
        try:
            next_process = all_pid.__next__()
            pid_name = next_process.name()
            # print(pid_name)
            if pid_name == 'chromedriver.exe':
                pid = next_process.pid
                # print(pid)
                return pid
        except:
            break程序逻辑
在调用selenium驱动后,获取驱动进程pid,再等待一段时间后,再次获取进程pid,如果两次pid的值相等,说明模拟器超时卡顿了,接下来清除该进程。
封装工具
对逻辑代码进行封装
def check(all_pid,func):
    while True:
        try:
            next_process = all_pid.__next__()
            pid_name = next_process.name()
            # print(pid_name)
            if func(pid_name):
                pid = next_process.pid
                # print(pid)
                return pid
        except:
            break然后通过调用工具方法
def option():
    ago_pid = None
    while not ago_pid:
        ago_pid = check(psutil.process_iter(),lambda item:item=='chromedriver.exe')
    print(ago_pid)
    time.sleep(2*60)
    now_pid = check(psutil.process_iter(),lambda item:item=='chromedriver.exe')
    print(now_pid)
    if ago_pid == now_pid:
        os.system('taskkill /f /im %s' % 'chrome.exe')
        os.system('taskkill /f /im %s' % 'chromedriver.exe')
同样可以达到和装饰器方法相同的效果,在实际运行自动化浏览器,如果遇到浏览器超时卡顿的问题,可以对浏览器进程进行实时监控。










