program story

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

inputbox 2020. 12. 30. 08:08
반응형

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


내가 사용하고 셀레늄을 브라우저를 실행합니다. 브라우저에 인증서 수락 여부를 묻는 웹 페이지 (URL)를 어떻게 처리 할 수 ​​있습니까?

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

Firefox

Internet Explorer 브라우저에서 다음과 같은 내용이 표시 될 수 있습니다.

여기에 이미지 설명 입력

Google 크롬에서 :

구글 크롬

내 질문을 반복합니다. Selenium (Python 프로그래밍 언어)을 사용하여 브라우저 (Internet Explorer, Firefox 및 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의 경우 인수 를 추가해야합니다 .--ignore-certificate-errors 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의 경우 acceptSslCerts원하는 기능 을 설정해야 합니다.

from selenium import webdriver

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

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

driver.close()

실제로 Desired Capabilities문서 에 따르면로 설정 acceptSslCerts기능 True은 일반 읽기 / 쓰기 기능이므로 모든 브라우저에서 작동해야합니다.

acceptSslCerts

부울

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


Firefox 용 작업 데모 :

>>> from selenium import webdriver

설정 acceptSslCertsFalse:

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

설정 acceptSslCertsTrue:

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

들어 크롬 우리가 사용할 수 있습니다 :

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

를 들어 인터넷 익스플로러 우리가 사용할 수 있습니다 :

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

Firefox Python의 경우 :

Firefox 자체 서명 된 인증서 버그가 수정되었습니다. 마리오네트 파이어 폭스 웹 드라이브 파이썬 스플린터로 SSL 인증서 수락

"acceptSslCerts"는 "acceptInsecureCerts"로 바꿔야합니다.

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

자바 스크립트 :

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

파이썬 셀레늄을 통해 헤드리스 크롬과 관련된이 질문에 오는 사람들에게는 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)

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

desired_capabilities = {
    "acceptInsecureCerts": True
}

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)

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


프로필과 드라이버를 생성하면 Firefox의 인증서 문제를 해결할 수 있습니다.

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

Just an update regarding this issue.

Require Drivers:

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)

Code

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

I was able to do this on .net c# with PhantomJSDriver with selenium web driver 3.1

 [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);
    }

And in C# (.net core) using Selenium.Webdriver and Selenium.Chrome.Webdriver like this:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--ignore-certificate-errors");
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),options))
{ 
  ...
}

Whenever I run into this issue with newer browsers, I just use AppRobotic Personal edition to click specific screen coordinates, or tab through the buttons and click.

Basically it's just using its macro functionality, but won't work on headless setups though.


I ran into the same issue with Selenium and Behat. If you want to pass the parameters via behat.yml, here is what it needs to look like:

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

I had the exact same issue. However when I tried opening the website manually in the browser the certificate was correct, but in the details the name was "DONOTTRUST".

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

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


이 문제에 대한 표준 결정이 아직없는 것 같습니다. 다시 말해, "인터넷 익스플로러, 모질라 또는 구글 크롬이든지 상관없이 인증을하세요"라고 말할 수 없습니다. 그러나 Mozilla Firefox에서 문제를 해결하는 방법을 보여주는 하나의 게시물을 찾았습니다. 관심이 있으시면 여기에서 확인할 수 있습니다 .

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

반응형