sourcecode

셀레늄을 통해 헤드리스 모드에서 크롬 브라우저를 시작하도록 크롬 드라이버를 구성하는 방법은 무엇입니까?

copyscript 2023. 8. 27. 09:46
반응형

셀레늄을 통해 헤드리스 모드에서 크롬 브라우저를 시작하도록 크롬 드라이버를 구성하는 방법은 무엇입니까?

저는 웹 스크레이핑을 위한 파이썬 스크립트를 만들고 있으며 패키지 중 하나로 크롬 드라이버를 사용하는 과정을 거쳤습니다.저는 이것이 팝업 창 없이 백그라운드에서 작동하기를 원합니다.Chromedriver에서 '헤드리스' 옵션을 사용하고 있는데 브라우저 창을 표시하지 않는 측면에서 작동하는 것처럼 보이지만 .exe 파일이 여전히 실행 중입니다.제가 말하는 것의 스크린샷을 보세요.스크린샷

ChromeDriver를 시작하기 위해 사용하는 코드는 다음과 같습니다.

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
options.add_argument('headless')
options.add_argument('window-size=0x0')
chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"

제가 하려고 했던 것은 옵션의 창 크기를 0x0으로 변경하는 것이지만 .exe 파일이 계속 뜨기 때문에 아무 효과가 있었는지 모르겠습니다.

어떻게 해야 할지 생각나는 거 있어요?

저는 파이썬 2.7 FYI를 사용하고 있습니다.

다음과 같이 표시되어야 합니다.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

이것은 Python 3.6을 사용하는 저에게 효과가 있습니다. 2.7에도 효과가 있을 것이라고 확신합니다.

2018-10-26 업데이트:최근에는 다음과 같은 작업을 수행할 수 있습니다.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

업데이트 2023-05-22: Chrome의 헤드리스 모드가 업그레이드되었으며 이제 헤드리스 모드와 헤드풀 모드가 동일한 구현으로 통합되었습니다.https://developer.chrome.com/articles/new-headless/ 을 참조하십시오.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless=new')
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

새로운 헤드리스 모드를 사용하려면,--headless=new명령줄 플래그:

chrome --headless=new

현재로서는 다음을 통해 이전 헤드리스 모드를 계속 사용할 수 있습니다.

chrome --headless=old

현재, 다음을 통과하고 있습니다.--headless명시적인 값이 없는 명령줄 플래그는 여전히 이전 헤드리스 모드를 활성화하지만 시간이 지남에 따라 이 기본값을 새 헤드리스 모드로 변경할 계획입니다.

13-10-2018년 답변 업데이트

Selenium 기반 ChromeDriver를 사용하여 구글 헤드리스 브라우징 컨텍스트를 시작하려면 다음의 인스턴스를 통해 속성을 설정하면 됩니다.Options()클래스는 다음과 같습니다.

  • 유효 코드 블록:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized")
    driver.quit()
    

2018년 4월 23일 답변 업데이트

모드에서 구글 을 프로그래밍 방식으로 호출하는 것은 다음과 같은 방법을 사용할 수 있게 됨에 따라 훨씬 쉬워졌습니다.

  • 설명서:

    set_headless(headless=True)
        Sets the headless argument
    
        Args:
            headless: boolean value indicating to set the headless option
    
  • 샘플 코드:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.set_headless(headless=True)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized")
    driver.quit()
    

참고: 인수는 내부적으로 구현됩니다.


2018년 3월 30일의 원답.

헤드리스 모드에서 Selenium Client 3.11.x, ChromeDriver v2.38Google Chrome v65.0.3325.181을 사용할 때는 다음 사항을 고려해야 합니다.

  • 헤드리스 모드에서 크롬을 호출하려면 인수를 추가해야 합니다.

  • 윈도우즈 OS 시스템의 경우 인수를 추가해야 합니다.

  • 헤드리스에 따라: --disable-gpu 플래그를 불필요하게 만듭니다. --disable-gpuLinux 시스템 및 MacOS에서는 플래그가 필요하지 않습니다.

  • SwiftShader가 헤드리스 모드에서 윈도우즈에서 어설션에 실패함에 따라 --disable-gpuWindows 시스템에서도 플래그가 필요 없게 됩니다.

  • 최대화된 뷰포트에는 인수가 필요합니다.

  • 다음은 뷰포트에 대한 세부 정보 링크입니다.

  • OS 보안 모델을 무시하려면 인수를 추가해야 할 수 있습니다.

  • 한 윈도우 코드 블록:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--headless") # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox') # Bypass OS security model
    options.add_argument('--disable-gpu')  # applicable to windows os only
    options.add_argument('start-maximized') # 
    options.add_argument('disable-infobars')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized on Windows OS")
    
  • 한 Linux 코드 블록:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--headless") # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox') # # Bypass OS security model
    options.add_argument('start-maximized')
    options.add_argument('disable-infobars')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path='/path/to/chromedriver')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized on Linux OS")
    

YouTube 동영상을 통한 단계

셀레늄을 통해 Chrome Browser를 최대화 모드로 초기화하는 방법

아우트로

파이썬으로 셀레늄에서 파이어폭스를 프로그래밍 방식으로 헤드리스로 만드는 방법은 무엇입니까?


tl; dr

여기 샌드박스 이야기 링크가 있습니다.

2020년 8월 20일 업데이트(아직 유효) - 이제 간단합니다!

chrome_options = webdriver.ChromeOptions()
chrome_options.headless = True

self.driver = webdriver.Chrome(
            executable_path=DRIVER_PATH, chrome_options=chrome_options)

업데이트됨 내 경우에는 정상적으로 작동합니다.

from selenium import webdriver

options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)

2020년에 막 바뀌었습니다.저한테는 잘 맞습니다.

그래서 코드를 수정한 후:

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
options.add_argument('--disable-gpu')
options.add_argument('--headless')
chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"

스크립트를 실행할 때 .exe 파일이 계속 표시됩니다.비록 이것이 "GPU 프로세스를 시작하는 데 실패했습니다"라는 추가 출력을 제거했지만,

결국 작동하게 된 것은 .bat 파일을 사용하여 Python 스크립트를 실행하는 것입니다.

그래서 기본적으로,

  1. 폴더인 경우 python 스크립트 저장
  2. 텍스트 편집기를 열고 다음 코드를 덤프합니다(물론 스크립트에 편집).

    c:\tau27\tau.예:\SampleFolder\ThisIsMyScript.py %*

  3. .txt 파일을 저장하고 확장자를 .bat로 변경합니다.

  4. 파일을 실행하려면 이 옵션을 두 번 클릭합니다.

명령 프롬프트에서 방금 스크립트가 열렸고 ChromeDriver는 내 화면 앞에 나타나지 않고 이 창에서 작동하여 문제를 해결하는 것 같습니다.

  1. .exe가 실행되고 있을 것입니다.Google에 따르면 - "헤드리스 모드에서 실행됩니다. 즉, UI 또는 디스플레이 서버 종속성 없이 실행됩니다."

  2. 추가하는 즉, " " " " " " " 2 " " 입니다.options.add_argument('--headless')

  3. 헤드리스 모드에서는 GPU를 비활성화하는 것이 좋습니다.options.add_argument('--disable-gpu')

Chrome Driver Manager를 사용해 보십시오.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager 
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.set_headless()
browser =webdriver.Chrome(ChromeDriverManager().install(),chrome_options=chrome_options)
browser.get('https://google.com')
# capture the screen
browser.get_screenshot_as_file("capture.png")

위의 솔루션은 클라우드 플레어 보호 기능이 있는 웹 사이트에서 작동하지 않습니다. 예:https://paxful.com/fr/buy-bitcoin.

options.add_argument("user-agent=Domino/5.0(Windows NT 6.1; Win64; x64) Apple WebKit/537.36(KHTML, Gecko와 유사) Chrome/84.0.4147.125 Safari/537.36")을 사용하여 에이전트를 수정합니다.

수정사항은 다음에서 찾을 수 있습니다.Selenium Python을 통해 정상/헤드리스 모드에서 ChromeDriver/Chrome을 사용하여 Cloudflare 웹사이트에 액세스하는 것의 차이점은 무엇입니까?

  
from chromedriver_py import binary_path
 
 
chrome_options = webdriver.ChromeOptions()
   chrome_options.add_argument('--headless')
   chrome_options.add_argument('--no-sandbox')
   chrome_options.add_argument('--disable-gpu')
   chrome_options.add_argument('--window-size=1280x1696')
   chrome_options.add_argument('--user-data-dir=/tmp/user-data')
   chrome_options.add_argument('--hide-scrollbars')
   chrome_options.add_argument('--enable-logging')
   chrome_options.add_argument('--log-level=0')
   chrome_options.add_argument('--v=99')
   chrome_options.add_argument('--single-process')
   chrome_options.add_argument('--data-path=/tmp/data-path')
   chrome_options.add_argument('--ignore-certificate-errors')
   chrome_options.add_argument('--homedir=/tmp')
   chrome_options.add_argument('--disk-cache-dir=/tmp/cache-dir')
   chrome_options.add_argument('user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')
   
  driver = webdriver.Chrome(executable_path = binary_path,options=chrome_options)

System.setProperty("webdriver.chrome.driver",
         "D:\\Lib\\chrome_driver_latest\\chromedriver_win32\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--window-size=1920x1080");
chromeOptions.addArguments("--disable-gpu"); 
chromeOptions.setHeadless(true);
ChromeDriver driver = new ChromeDriver(chromeOptions);

처음에, 저는 셀레늄과 함께 크롬에 헤드리스 모드를 사용하는 동안 빈 화면이라는 문제에 직면했습니다.

사용자 에이전트를 재정의하려고 했지만 도움이 되지 않았습니다.그리고 설명서에서 Chrome 버전 109의 경우 다음과 같은 방법으로 헤드리스 모드를 설정할 것을 권장합니다.

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

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/chromiumOptions.html#setHeadless(부울)

헤드리스 모드를 시작하는 전체 코드는 다음과 같습니다.

ChromeOptions options = new ChromeOptions()
options.addArguments("--window-size=1920,1080")
options.addArguments("--headless=new") 
options.setExperimentalOption("w3c", false) 
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome('/usr/bin/chromedriver', options=chrome_options)
driver.get('https://www.example.com')
print(driver.title)
driver.quit()
chromeoptions=add_argument("--no-sandbox");
add_argument("--ignore-certificate-errors");
add_argument("--disable-dev-shm-usage'")

지원되지 않는 브라우저입니다.

솔루션:

Open Browser    ${event_url}    ${BROWSER}   options=add_argument("--no-sandbox"); add_argument("--ignore-certificate-errors"); add_argument("--disable-dev-shm-usage'")

사이에 공백을 추가하는 것을 잊지 마십시오.${BROWSER}옵션들

크롬 드라이버를 숨길 수 있는 옵션이 있습니다.셀레늄 4의 알파 및 베타 버전의 exe 창.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows
chrome_service = ChromeService('chromedriver', creationflags=CREATE_NO_WINDOW)
driver = webdriver.Chrome(service=chrome_service) # No longer console window opened, niether will chromedriver output

여기서 확인하실 수 있습니다.베타 또는 알파 버전을 pip 설치하려면 "pip install selenium==4.0.0.a7" 또는 "pip install selenium==4.0.0.b4"(a7은 알파-7을 의미하고 b4는 베타-4를 의미하므로 원하는 다른 버전의 경우 명령을 수정할 수 있습니다.)python에서 라이브러리의 특정 버전을 가져오려면 여기를 참조하십시오.

최근 업데이트

최근에 Chrome의 헤드리스 모드에서 수행되는 업데이트가 있습니다.깃발--headless이제 수정되었으며 아래와 같이 사용할 수 있습니다.

크롬 버전 109 이상의 경우--headless=new플래그를 사용하면 헤드리스 모드에서 모든 기능의 Chrome 브라우저를 탐색할 수 있습니다.Chrome 버전 108 이하(버전 96까지)의 경우,--headless=chrome옵션은 우리에게 헤드리스 크롬 브라우저를 제공할 수 있습니다.

자, 이제.

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

위에서 언급한 것처럼 헤드리스 모드의 최신 버전의 Chrome.

Chrome 버전에서는 아래 내용이 잘 작동합니다.110.0.5481.104

chrome_driver_path = r"E:\driver\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')

//New Update
options.add_argument("--headless=new")  

options.binary_location = r"C:\Chrome\Application\chrome.exe"
browser = webdriver.Chrome(chrome_driver_path, options=options)
browser.get('https://www.google.com')

실행 파일 경로가 감소했기 때문입니다.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

from selenium.webdriver import ChromeOptions
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

options = ChromeOptions()
options.add_argument('--headless=new')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

2021년 8월 업데이트:

가장 빠른 방법은 다음과 같습니다.

from selenium import webdriver  

options = webdriver.ChromeOptions()
options.set_headless = True
driver = webdriver.Chrome(options=options)

options.headless = True사용되지 않습니다.

언급URL : https://stackoverflow.com/questions/46920243/how-to-configure-chromedriver-to-initiate-chrome-browser-in-headless-mode-throug

반응형