programing

셀레늄을 사용하여 인증서를 처리하는 방법은 무엇입니까?

kakaobank 2023. 5. 27. 11:52
반응형

셀레늄을 사용하여 인증서를 처리하는 방법은 무엇입니까?

나는 브라우저를 실행하기 위해 셀레늄을 사용하고 있습니다.브라우저에서 인증서를 수락하도록 요청하는 웹 페이지(URL)를 처리하려면 어떻게 해야 합니까?

Firefox에서는 다음과 같은 웹 사이트에서 인증서를 수락하도록 요청할 수 있습니다.

파이어폭스

Internet Explorer 브라우저에서 다음과 같은 메시지가 표시될 수 있습니다.

여기에 이미지 설명 입력

Google Chrome의 경우:

구글 크롬

질문을 반복합니다.셀레늄(파이썬 프로그래밍 언어)으로 브라우저(인터넷 익스플로러, 파이어폭스구글 크롬)를 시작할 때 사이트의 인증서 수락을 자동화하려면 어떻게 해야 합니까?

Firefox의 경우 다음을 설정해야 합니다.accept_untrusted_certs FirefoxProfile()에 대한 선택권.True:

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True

driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://cacert.org/')

driver.close()

Chrome의 경우 추가해야 합니다. ChromeOptions()인수:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('ignore-certificate-errors')

driver = webdriver.Chrome(chrome_options=options)
driver.get('https://cacert.org/')

driver.close()

Internet Explorer의 경우 원하는 기능을 설정해야 합니다.

from selenium import webdriver

capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities['acceptSslCerts'] = True

driver = webdriver.Ie(capabilities=capabilities)
driver.get('https://cacert.org/')

driver.close()

사실, 문서에 따르면, 설정은acceptSslCerts할 수 있는 능력.True일반적인 읽기/쓰기 기능이므로 모든 브라우저에서 작동합니다.

SslCerts 수락

부울의

세션이 기본적으로 모든 SSL 인증서를 수락할지 여부입니다.


Firefox용 작업 데모:

>>> from selenium import webdriver

설정acceptSslCerts로.False:

>>> capabilities = webdriver.DesiredCapabilities().FIREFOX
>>> capabilities['acceptSslCerts'] = False
>>> driver = webdriver.Firefox(capabilities=capabilities)
>>> driver.get('https://cacert.org/')
>>> print(driver.title)
Untrusted Connection
>>> driver.close()

설정acceptSslCerts로.True:

>>> capabilities = webdriver.DesiredCapabilities().FIREFOX
>>> capabilities['acceptSslCerts'] = True
>>> driver = webdriver.Firefox(capabilities=capabilities)
>>> driver.get('https://cacert.org/')
>>> print(driver.title)
Welcome to CAcert.org
>>> driver.close()

Firefox의 경우:

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
myprofile.setAcceptUntrustedCertificates(true);
myprofile.setAssumeUntrustedCertificateIssuer(true);
WebDriver driver = new FirefoxDriver(myprofile);

Chrome의 경우 다음을 사용할 수 있습니다.

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--ignore-certificate-errors"));
driver = new ChromeDriver(capabilities);

Internet Explorer의 경우 다음을 사용할 수 있습니다.

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);      
Webdriver driver = new InternetExplorerDriver(capabilities);

Firefox Python의 경우:

Firefox 자체 서명 인증서 버그가 수정되었습니다. marionette Firefox webdrive python splinter와 함께 ssl cert를 수락합니다.

"acceptSslCerts"는 "accept"로 대체되어야 합니다.안전하지 않은 인증서"

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

caps = DesiredCapabilities.FIREFOX.copy()
caps['acceptInsecureCerts'] = True
ff_binary = FirefoxBinary("path to the Nightly binary")

driver = webdriver.Firefox(firefox_binary=ff_binary, capabilities=caps)
driver.get("https://expired.badssl.com")

파이썬 셀레늄을 통해 헤드리스 크롬과 관련된 이 질문을 하는 사람들은 https://bugs.chromium.org/p/chromium/issues/detail?id=721739#c102 이 유용할 것입니다.

당신도 할 수 있을 것 같습니다.

chrome_options = Options()
chrome_options.add_argument('--allow-insecure-localhost')

또는 다음과 같은 노선을 따르는 것(파이썬에 적응해야 할 수 있음):

ChromeOptions options = new ChromeOptions()
DesiredCapabilities caps = DesiredCapabilities.chrome()
caps.setCapability(ChromeOptions.CAPABILITY, options)
caps.setCapability("acceptInsecureCerts", true)
WebDriver driver = new ChromeDriver(caps)

C#(.net core)에서는 다음을 사용합니다.Selenium.Webdriver그리고.Selenium.Chrome.Webdriver다음과 같이:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--ignore-certificate-errors");
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),options))
{ 
  ...
}
    ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
    options.setAcceptInsecureCerts(true);

Javascript:

const capabilities = webdriver.Capabilities.phantomjs();
capabilities.set(webdriver.Capability.ACCEPT_SSL_CERTS, true);
capabilities.set(webdriver.Capability.SECURE_SSL, false);
capabilities.set('phantomjs.cli.args', ['--web-security=no', '--ssl-protocol=any', '--ignore-ssl-errors=yes']);
const driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome(), capabilities).build();

셀레늄 파이썬에서 설정해야 합니다.desired_capabilities다음과 같이:

desired_capabilities = {
    "acceptInsecureCerts": True
}

저는 셀레늄과 베하트와 같은 문제에 부딪혔습니다.매개 변수를 전달하려면behat.yml다음과 같이 표시해야 합니다.

default:
    extensions:
        Behat\MinkExtension:
            base_url: https://my-app.com
            default_session: selenium2
            selenium2:
                browser: firefox
                capabilities:
                    extra_capabilities:
                        acceptInsecureCerts: true

프로필을 만든 다음 드라이버를 만들면 Firefox의 인증서 문제를 해결하는 데 도움이 됩니다.

var profile = new FirefoxProfile();
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris","DESIREDURL");
driver = new FirefoxDriver(profile);

Firefox를 사용하여 이 문제를 해결했지만 위의 솔루션이 작동하지 않는 경우 아래 코드를 사용해 보십시오(원래 답변은 여기에 있습니다).

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.DEFAULT_PREFERENCES['frozen']['marionette.contentListener'] = True
profile.DEFAULT_PREFERENCES['frozen']['network.stricttransportsecurity.preloadlist'] = False
profile.DEFAULT_PREFERENCES['frozen']['security.cert_pinning.enforcement_level'] = 0
profile.set_preference('webdriver_assume_untrusted_issuer', False)
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", temp_folder)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk",
                   "text/plain, image/png")
driver = webdriver.Firefox(firefox_profile=profile)
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);

나는 그것을 크롬 브라우저가 있는 자바에 사용했습니다. 그것은 잘 작동합니다.

브라우저의 인증서 저장소에서 필요한 인증서를 제외한 모든 인증서를 삭제한 다음 인증서가 하나만 있을 때 자동으로 인증서를 선택하도록 브라우저를 구성합니다.

이 문제에 대한 업데이트일 뿐입니다.

필요한 드라이버:

Linux: Centos 7 64bit, Window 7 64bit

Firefox: 52.0.3

Selenium Webdriver: 3.4.0 (Windows), 3.8.1 (Linux Centos)

GeckoDriver: v0.16.0 (Windows), v0.17.0 (Linux Centos)

코드

System.setProperty("webdriver.gecko.driver", "/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver");

ProfilesIni ini = new ProfilesIni();


// Change the profile name to your own. The profile name can 
// be found under .mozilla folder ~/.mozilla/firefox/profile. 
// See you profile.ini for the default profile name

FirefoxProfile profile = ini.getProfile("default"); 

DesiredCapabilities cap = new DesiredCapabilities();
cap.setAcceptInsecureCerts(true);

FirefoxBinary firefoxBinary = new FirefoxBinary();

GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)
    .usingDriverExecutable(new 
File("/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver"))
    .usingAnyFreePort()
    .usingAnyFreePort()
    .build();
try {
    service.start();
} catch (IOException e) {
    e.printStackTrace();
}

FirefoxOptions options = new FirefoxOptions().setBinary(firefoxBinary).setProfile(profile).addCapabilities(cap);

driver = new FirefoxDriver(options);
driver.get("https://www.google.com");

System.out.println("Life Title -> " + driver.getTitle());
driver.close();

저는 팬텀J로 .netc#에서 이것을 할 수 있었습니다.셀레늄 웹 드라이버 3.1이 포함된 SD 드라이버

 [TestMethod]
    public void headless()
    {


        var driverService = PhantomJSDriverService.CreateDefaultService(@"C:\Driver\phantomjs\");
        driverService.SuppressInitialDiagnosticInformation = true;
        driverService.AddArgument("--web-security=no");
        driverService.AddArgument("--ignore-ssl-errors=yes");
        driver = new PhantomJSDriver(driverService);

        driver.Navigate().GoToUrl("XXXXXX.aspx");

        Thread.Sleep(6000);
    }

최신 브라우저에서 이 문제가 발생할 때마다 AppRobotic Personal 버전을 사용하여 특정 화면 좌표를 클릭하거나 버튼을 눌러 클릭합니다.

기본적으로 매크로 기능만 사용하지만 헤드리스 설정에서는 작동하지 않습니다.

저도 똑같은 문제가 있었습니다.그러나 브라우저에서 수동으로 웹사이트를 열려고 했을 때 인증서는 정확했지만 세부 정보에서 이름은 "DONOTRUST"였습니다.

인증서 차이는 백그라운드에서 실행 중인 Fiddler가 암호화하기 전에 모든 HTTPS 콘텐츠를 해독했기 때문에 발생했습니다.

내 문제를 해결하려면 기계에서 Fiddler를 닫으십시오.Fiddler를 열어 두어야 하는 경우 Fiddler 설정에서 SSL 암호 해독을 선택 취소할 수 있습니다.

.NET의 경우 다음과 같은 이점이 있었습니다.

var chromeOptions = new ChromeOptions { AcceptInsecureCertificates = true };

거의 대부분의 경우, 크롬 드라이버 옵션은 안전하지 않은 인증서가 감지될 때 브라우저 실행을 중지하지 말고 정상적으로 진행하도록 지시합니다.

간단한 접근법,

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService

# pip install webdriver-manager
from webdriver_manager.chrome import ChromeDriverManager



def get_chrome_capabilities():
    caps = webdriver.DesiredCapabilities.CHROME
    caps['acceptSslCerts'] = True
    caps['acceptInsecureCerts'] = True
    opts = webdriver.ChromeOptions()
    caps.update(opts.to_capabilities())
    return caps


# ChromeDriveManager to automate and download webdriver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(
  service=service,
  desired_capabilities=get_chrome_capabilities(),
)

# Use this instead of the above if you are already setup
# driver = webdriver.Chrome(desired_capabilities=get_chrome_capabilities())


driver.get("http://www.google.com")
assert "google" in driver.page_source
driver.quit()

아직도 이 문제에 대한 표준적인 결정이 없는 것 같습니다.즉, 여전히 "인터넷 익스플로러, Mozilla 또는 Google Chrome이라면 무엇이든 인증을 수행하십시오."라고 말할 수 없습니다.하지만 Mozilla Firefox에서 문제를 해결하는 방법을 보여주는 게시물을 하나 찾았습니다.만약 당신이 그것에 관심이 있다면, 당신은 여기에서 확인할 수 있습니다.

언급URL : https://stackoverflow.com/questions/24507078/how-to-deal-with-certificates-using-selenium

반응형