如何在 Python 中用 Selenium 运行无头 Chrome



我正在尝试一些关于硒的东西,我真的希望我的脚本快速运行。

我认为使用无头Chrome运行我的脚本会让它更快。

首先,这个假设是否正确,或者我是否使用无头驱动程序运行脚本无关紧要?

我希望无头Chrome工作,但不知何故它无法正常工作。我尝试了不同的东西,大多数人建议它会像十月更新中所说的那样工作:

如何配置ChromeDriver以通过Selenium在无头模式下启动Chrome浏览器?

但是当我尝试这样做时,我看到了奇怪的控制台输出,它似乎仍然不起作用。

任何提示表示赞赏。

要运行 chrome-headless 只需通过chrome_options.add_argument添加--headless,例如:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
# chrome_options.add_argument("--disable-extensions")
# chrome_options.add_argument("--disable-gpu")
# chrome_options.add_argument("--no-sandbox") # linux only
chrome_options.add_argument("--headless=new") # for Chrome >= 109
# chrome_options.add_argument("--headless")
# chrome_options.headless = True # also works
driver = webdriver.Chrome(options=chrome_options)
start_url = "https://duckgo.com"
driver.get(start_url)
print(driver.page_source.encode("utf-8"))
# b'<!DOCTYPE html><html xmlns="http://www....
driver.quit()

所以我的想法是,使用无头铬运行它会让我 脚本编写速度更快。

尝试使用--disable-extensions--disable-gpu等 chrome 选项并对其进行基准测试,但我不会有实质性的改进。


参考资料:无头铬

安装并运行容器化 Chrome:

docker pull selenium/standalone-chrome
docker run --rm -d -p 4444:4444 --shm-size=2g selenium/standalone-chrome

使用webdriver.Remote进行连接:

driver = webdriver.Remote('http://localhost:4444/wd/hub', webdriver.DesiredCapabilities.CHROME)
driver.set_window_size(1280, 1024)
driver.get('https://www.google.com')
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path="./chromedriver", options=chrome_options)
url = "https://stackoverflow.com/questions/53657215/running-selenium-with-headless-chrome-webdriver"
driver.get(url)
sleep(5)
h1 = driver.find_element_by_xpath("//h1[@itemprop='name']").text
print(h1)

然后我在本地机器上运行脚本

➜ python script.py
Running Selenium with Headless Chrome Webdriver

它正在工作,并且使用无头铬。

如果您使用的是Linux环境,则可能还必须添加--no-sandbox以及特定的窗口大小设置。如果正确设置用户容器,则 Windows 上不需要--no-sandbox标志。

仅在 Windows 上使用--disable-gpu。其他平台不再需要它。--disable-gpu标志是一些错误的临时解决方法。

//Headless chrome browser and configure
WebDriverManager.chromedriver().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("disable-gpu");
//          chromeOptions.addArguments("window-size=1400,2100"); // Linux should be activate
driver = new ChromeDriver(chromeOptions);

最近在Chrome的无头模式下进行了更新。 标志--headless现已修改,可以按如下方式使用

  • 对于 Chrome 版本 109 及更高版本,--headless=new标志允许我们在无头模式下探索 Chrome 浏览器的全部功能。
  • 对于Chrome版本108及更低版本(直到版本96),--headless=chrome选项将为我们提供无头Chrome浏览器。

所以,让我们添加

options.add_argument("--headless=new")

如上所述,适用于无头模式下较新版本的 Chrome。

一旦你安装了硒和网络驱动程序。下面为我在 linux 集群上使用无头 Chrome 工作:

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("--disable-extensions")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")
options.add_experimental_option("prefs",{"download.default_directory":"/databricks/driver"})
driver = webdriver.Chrome(chrome_options=options)

Todo(在无头服务器Debian Linux 9.4上测试):

  1. 这样做:

    # install chrome
    curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
    echo "deb [arch=amd64]  http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
    apt-get -y update
    apt-get -y install google-chrome-stable
    # install chrome driver
    wget https://chromedriver.storage.googleapis.com/77.0.3865.40/chromedriver_linux64.zip
    unzip chromedriver_linux64.zip
    mv chromedriver /usr/bin/chromedriver
    chown root:root /usr/bin/chromedriver
    chmod +x /usr/bin/chromedriver
    
  2. 安装硒:

    pip install selenium
    

    并运行此 Python 代码:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    options = Options()
    options.add_argument("no-sandbox")
    options.add_argument("headless")
    options.add_argument("start-maximized")
    options.add_argument("window-size=1900,1080"); 
    driver = webdriver.Chrome(chrome_options=options, executable_path="/usr/bin/chromedriver")
    driver.get("https://www.example.com")
    html = driver.page_source
    print(html)
    
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path=r"C:Program 
FilesGoogleChromeApplicationchromedriver.exe", options=chrome_options)

这对我来说没关系。

如接受的答案所述:

options.add_argument("--headless")

这些提示可能有助于加快速度,特别是对于无头:

在无头中你可以做很多在非无头中做不到的事情

由于您将使用Chrome Headless,我发现添加此功能可将CPU使用率降低约20%(在查看htop时,我发现这是CPU和内存占用者)

--禁用崩溃报告器

这只会在你以无头方式运行时禁用 这可能会加快速度!!

我的设置目前如下,我将 CPU(但仅节省少量时间)减少了大约 20%:

options.add_argument("--no-sandbox");
options.add_argument("--disable-dev-shm-usage");
options.add_argument("--disable-renderer-backgrounding");
options.add_argument("--disable-background-timer-throttling");
options.add_argument("--disable-backgrounding-occluded-windows");
options.add_argument("--disable-client-side-phishing-detection");
options.add_argument("--disable-crash-reporter");
options.add_argument("--disable-oopr-debug-crash-dump");
options.add_argument("--no-crash-upload");
options.add_argument("--disable-gpu");
options.add_argument("--disable-extensions");
options.add_argument("--disable-low-res-tiling");
options.add_argument("--log-level=3");
options.add_argument("--silent");

我发现这是一个非常好的命令行开关列表(我认为是完整列表),并带有解释:https://peter.sh/experiments/chromium-command-line-switches/

这里还提到了您可以关闭的一些其他功能:https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md

我希望这对某人有所帮助

在无头环境中运行 Chrome 有不同的方法。(您将在此答案中找到更多详细信息:https://stackoverflow.com/a/73840130/7058266)

一、标准无头模式:(比有头模式快,但您可能会遇到兼容性问题。

options.add_argument("--headless")

然后是Chrome 109的新Chrome无头模式:(它的运行速度与标题模式相同,因为两者几乎相同。

options.add_argument("--headless=new")

(在Chrome 96和108之间,这种新模式曾经是--headless=chrome,但它被重命名了。

如果使用无头显示器,您也可以在无头环境中运行常规 Chrome,例如 Xvfb 和控制它的 Python 程序,例如 pyvirtualdisplay。(见 https://stackoverflow.com/a/6300672/7058266 和 https://stackoverflow.com/a/23447450/7058266)

from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Chrome()
driver.get('http://www.google.com')
driver.quit()
display.stop()

为了提高兼容性,您可以尝试将上述内容与新的Chrome无头模式结合使用:

options.add_argument("--headless=new")

您可以在 Python 中运行带有 Selenium 的无头 Chrome,如下所示。 *--headless=new更好,因为--headless根据无头正在消失使用旧的无头模式!

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--headless=new") # Here
driver = webdriver.Chrome(options=options)

或:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless=new") # Here
driver = webdriver.Chrome(options=options)

此外,下面的例子可以用无头的Chrome,Selenium,pytest-django和Django测试Django Admin。 *我的回答解释了如何使用多个无头浏览器(Chrome,Microsoft Edge和Firefox),Selenium,pytest-django和Django测试Django Admin:

# "tests/test_1.py"
import pytest
from selenium import webdriver
from django.test import LiveServerTestCase
@pytest.fixture(scope="class")
def chrome_driver_init(request):
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
chrome_driver = webdriver.Chrome(options=options)
request.cls.driver = chrome_driver
yield
chrome_driver.close()
@pytest.mark.usefixtures("chrome_driver_init")
class Test_URL_Chrome(LiveServerTestCase):
def test_open_url(self):
self.driver.get(("%s%s" % (self.live_server_url, "/admin/")))
assert "Log in | Django site admin" in self.driver.title

或:

# "tests/conftest.py"
import pytest
from selenium import webdriver
@pytest.fixture(scope="class")
def chrome_driver_init(request):
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
chrome_driver = webdriver.Chrome(options=options)
request.cls.driver = chrome_driver
yield
chrome_driver.close()
# "tests/test_1.py"
import pytest
from django.test import LiveServerTestCase
@pytest.mark.usefixtures("chrome_driver_init")
class Test_URL_Chrome(LiveServerTestCase):
def test_open_url(self):
self.driver.get(("%s%s" % (self.live_server_url, "/admin/")))
assert "Log in | Django site admin" in self.driver.title

最新更新