Python中使用selenium和Chrome进行爬虫开发,如何启用headless模式?
用 selenium+Chrome 开发爬虫时,想使用 Chrome 的 headless 模式,用了以下的语句,结果发现无效,浏览器依然还会出现,请问正确的写法应该是什么呢?感谢!
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument(’–headless’)
chrome_options.add_argument(’–disable-gpu’)
driver =webdriver.Chrome()
Python中使用selenium和Chrome进行爬虫开发,如何启用headless模式?
记得有 headless 的 chrome 驱动的,一个 exe 程序,不需要设置别的
在Python的Selenium中启用Chrome的headless模式很简单,主要是在创建WebDriver时添加--headless参数。下面是一个完整的示例代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 创建Chrome选项对象
chrome_options = Options()
# 启用headless模式
chrome_options.add_argument("--headless")
# 可选:在headless模式下禁用GPU加速(某些系统需要)
chrome_options.add_argument("--disable-gpu")
# 可选:禁用沙箱模式(在Linux等环境中可能需要)
chrome_options.add_argument("--no-sandbox")
# 可选:禁用/dev/shm使用(在Docker等环境中可能需要)
chrome_options.add_argument("--disable-dev-shm-usage")
# 创建WebDriver实例
driver = webdriver.Chrome(options=chrome_options)
# 现在可以正常使用driver进行爬虫操作
try:
driver.get("https://www.example.com")
print("页面标题:", driver.title)
# 其他爬虫操作...
finally:
driver.quit()
关键点说明:
- 导入
Options类来配置Chrome选项 - 使用
add_argument("--headless")启用无头模式 - 通过
options参数将配置传递给webdriver.Chrome() - 创建driver后,所有操作都和普通模式一样,只是没有浏览器界面
如果你用的是新版Selenium(4.8+),还可以用更简洁的方式:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service()
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(service=service, options=options)
记得根据你的Chrome版本安装对应版本的ChromeDriver。
总结:加个--headless参数就行。
driver =webdriver.Chrome(chrome_options=chrome_options)
我用 J***r 根本不需要驱动什么的,直接运行,还能操作浏览器
2 楼正解 是你没用 options
self.driver = webdriver.Chrome(executable_path=chrome_driver, chrome_options=chrome_options)
还应该有 chrome 的 binary path 和 driver 的 path 你都没加为啥也能运行。。。
在系统环境变量里就不需要指定了
selenium 使用 chrome 的 headless 模式: https://www.yuxianghe.net/article/50
如果是 windows 环境,确保你的 chrome 浏览器版本是 60+,不然也不行。
官方回答:
Caution: Headless mode is available on Mac and Linux in Chrome 59. Windows support is coming in Chrome 60. To check what version of Chrome you have, open chrome://version.
用 splinter 很方便就实现了。
pip install splinter<br>from splinter import Browser<br>browser = Browser('chrome', headless=True)<br>
谢谢,我先学习一下这篇文章
谢谢,可惜无法翻墙看不了
感谢,我试试看,看起来很方便
browser = Browser(‘chrome’, headless=True)
请问上面语句返回的 browser 对象如何与 selenium 的 webdriver 结合起来使用,使得可以操作 selenium 的 webdriver 方法返回的对象呢?
你没发现你没用你的 chrome_options 吗,2 楼正解
写了下面的代码,运行时是不会出现 chrome 浏览器,但是总是在一开始还是会弹出 chromedriver.exe 的命令窗口,请问这个弹窗要如何才能取消呢?感谢!
chrome_options = Options()
chrome_options.add_argument(’–headless’)
chrome_options.add_argument(’–disable-gpu’)
driver =webdriver.Chrome(chrome_options=chrome_options)
详细内容可以查看:
Splinter 官方文档: https://splinter.readthedocs.io/en/latest/
Splinter 中文文档: http://splinter-docs-zh-cn.readthedocs.io/zh/latest/
感谢!

