python使用phantomJS循环for爬取多个页面时,解决内存持续变大而报错“ConnectionResetError: [WinError 10054]远程主机强迫关闭了一个现有的连接”的问题...

首先声明,我是一个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

 

转载于:https://www.cnblogs.com/Berry-wxn/p/10998371.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值