| 首先声明,我是一个Python小白,想了个蠢办法,但觉得很实用。哈哈哈!!! Python使用phantomJS循环for爬取页面时,phantomJS占用的内存会越来越大,直接报错“ConnectionResetError: [WinError 10054]远程主机强迫关闭了一个现有的连接”,在网上查过很多办法都没有解决,现在有个简单的办法解决并让程序持续运行。 办法是:在抛出异常时,先关闭phantomJS,再新建一个phantomJS,把报错的这一次执行一遍(因为报错,这个爬取的内容不会执行存储下来,所以再执行这一次)。  
 from selenium import webdriver
service_args=[]
service_args.append('--load-images=no')  ##关闭图片加载   如果只爬取文字,不需要图片,关闭图片加载可以极大提升爬取网页速度
service_args.append('--disk-cache=yes')  ##开启缓存
service_args.append('--ignore-ssl-errors=true') ##忽略https错误
url = "https://www.baidu.com/"  #以爬取百度首页为例
driver = webdriver.PhantomJS(executable_path=r'C:\phantomjs\phantomjs-2.1.1-windows\bin\phantomjs.exe', service_args=service_args)
for ing in range(1, 10000):  # 执行99999次
     try:
         driver.get(url)
         directory = "./htmls/" + str(ing) + ".html" #把爬取的页面存到htmls文件夹下,命名为“数字.html”
         with open(directory, 'w') as file:
             file.write(driver.page_source)
             file.close()except Exception as e:
 print(e)
         # 当内存达到一定程度后,系统会报错,
         # 所以在抛出异常的时候,先关闭phantomJS,再新建一个phantomJS,
         # 把报错的这一次执行一遍(因为报错,这个爬取的内容不会执行存储下来,所以再执行这一次)
         driver.quit() #关闭
         driver = webdriver.PhantomJS(executable_path=r'C:\phantomjs\phantomjs-2.1.1-windows\bin\phantomjs.exe', service_args=service_args) #再创建一个phantomJS
         driver.get(url)
 directory = "./htmls/" + str(ing) + ".html"
         with open(directory, 'w') as file:
             file.write(driver.page_source)
             file.close()
 driver.quit() #循环结束,关闭driver
   |