首先聲明,我是一個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