如何在 Python 中使用 Headless Chrome Webdriver 运行 Selenium?

问题描述 投票:0回答:11

我正在尝试使用 selenium 进行一些操作,我真的希望我的脚本能够快速运行。

我认为使用无头 Chrome 运行我的脚本会使其速度更快。

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

我希望无头 Chrome 能够工作,但不知何故它无法正常工作。我尝试了不同的方法,大多数人建议它可以按照十月更新中的说明工作:

如何配置ChromeDriver通过Selenium以Headless模式启动Chrome浏览器?

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

任何提示表示赞赏。

python google-chrome selenium-webdriver selenium-chromedriver google-chrome-headless
11个回答
206
投票

要运行 chrome-headless 只需通过

--headless
添加
chrome_options.add_argument
,例如:

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")
# 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 选项并对其进行基准测试,但我不认为会有实质性改进。


参考文献:headless-chrome


22
投票

安装并运行容器化 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')

9
投票
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

它正在工作,并且与无头 Chrome 一起使用。


6
投票

如果您使用的是 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);

4
投票

最近Chrome的headless模式进行了更新。 标志

--headless
现已修改,可以按如下方式使用

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

所以,让我们添加

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

对于上面提到的无头模式下的较新版本的 Chrome。


3
投票

安装了 selenium 和网络驱动程序后。下面是我在 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)

2
投票

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)
    

2
投票
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 
Files\Google\Chrome\Application\chromedriver.exe", options=chrome_options)

这对我来说没问题。


2
投票

正如已接受的答案所述:

options.add_argument("--headless")

这些技巧可能有助于加快速度,尤其是对于无头设备:

有很多事情你可以在无头模式中做,而在非无头模式中则不能做

由于您将使用 Chrome Headless,我发现添加此功能可以减少大约 20% 的 CPU 使用率(在查看 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

我希望这对某人有帮助


0
投票

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

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

options.add_argument("--headless")

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

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

(在 Chrome 96 和 108 之间,该新模式曾经是

--headless=chrome
,但已重命名。)

如果使用无头显示器(例如 Xvfb)以及控制它的 Python 程序(例如 pyvirtualdisplay),您还可以在无头环境中运行常规 Chrome。 (请参阅https://stackoverflow.com/a/6300672/7058266https://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 headless 模式结合起来:

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

0
投票

您可以使用 Google Chrome 以无头模式运行 Selenium,如下所示。 *

--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)

此外,下面的示例可以使用 Selenium、Google Chrome、pytest-djangoDjango 来测试 Django Admin:

# "tests/test.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()

@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.py"

import pytest

@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
© www.soinside.com 2019 - 2024. All rights reserved.