加入chrome 进程强制退出流程。防止进程一只存在消耗资源。
This commit is contained in:
@@ -90,6 +90,13 @@ def fetch_images(post_url):
|
||||
options.add_argument('--headless') # 使用新的headless模式
|
||||
options.add_argument('--disable-gpu')
|
||||
options.add_argument('--disable-dev-shm-usage') # 添加Linux特定配置
|
||||
# 添加更多参数以确保Chrome进程能够正确退出
|
||||
options.add_argument('--no-sandbox')
|
||||
options.add_argument('--disable-extensions')
|
||||
options.add_argument('--disable-software-rasterizer')
|
||||
options.add_argument('--remote-debugging-port=0')
|
||||
options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
||||
options.add_experimental_option('useAutomationExtension', False)
|
||||
|
||||
options.headless = True
|
||||
# 根据操作系统选择不同的ChromeDriver路径处理方式
|
||||
@@ -123,13 +130,28 @@ def fetch_images(post_url):
|
||||
|
||||
logger.info(f"已爬取 {url},找到 {len(img_elements)} 张图片")
|
||||
|
||||
driver.quit()
|
||||
# 不在这里调用quit,统一在finally中处理
|
||||
return images
|
||||
except Exception as e:
|
||||
logger.info(f"爬取 {post_url} 失败: {e}")
|
||||
return []
|
||||
finally:
|
||||
driver.quit()
|
||||
# 确保在所有情况下都能正确关闭Chrome浏览器
|
||||
try:
|
||||
if driver is not None:
|
||||
driver.quit()
|
||||
logger.debug("Chrome浏览器已正常关闭")
|
||||
except Exception as e:
|
||||
logger.error(f"关闭Chrome浏览器时出错: {e}")
|
||||
# 在极端情况下,尝试使用系统命令强制终止Chrome进程
|
||||
try:
|
||||
if os.name == 'nt': # Windows
|
||||
os.system('taskkill /f /im chrome.exe /t')
|
||||
else: # Linux
|
||||
os.system('pkill -f chrome')
|
||||
logger.warning("已尝试强制终止Chrome进程")
|
||||
except Exception as kill_error:
|
||||
logger.error(f"强制终止Chrome进程失败: {kill_error}")
|
||||
|
||||
|
||||
def download_image(img_url, folder_path, img_index, max_retries=3):
|
||||
|
||||
Reference in New Issue
Block a user