Selenium 2 WebDriver для использования собственного профиля - PullRequest
4 голосов
/ 05 января 2011

Я пытаюсь автоматизировать взаимодействие с веб-сайтом, который генерирует документы с помощью приложения MIME-типа / vnd.wap.xhtml + xml.Я использую Selenium 2, WebDriver и FirefoxProfile.

Поскольку Firefox не обрабатывает упомянутый выше тип MIME, мне нужно запустить Firefox с расширением XHTML Mobile Profile (https://addons.mozilla.org/en-US/firefox/addon/1345/).

После создания профиля FireFox - я назвал его «selenium» - и установки расширения Mobile Profile, я попытался использовать фрагменты кода в разделе «Советы и хитрости» документа «Selenium 2.0 и WebDriver» (http://seleniumhq.org/docs/09_webdriver.html#htmlunit-driver).

Подход № 1 выглядит следующим образом:

ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("selenium");
profile.setPreference("general.useragent.override", "User Agent string to force application/vnd.wap.xhtml+xml content..");
FirefoxDriver driver = new FirefoxDriver(profile);
driver.get("http://www.mobilesite.com/");
WebElement element = driver.findElement(By.tagName("body"));

Подход № 2 выглядит следующим образом:

File profileDir = new File("/path/to/custom/profile/with/extension/ffprofile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.setPreference("general.useragent.override", "same user agent string as above");
FirefoxDriver driver = new FirefoxDriver(profile);
driver.get("http://www.mobilesite.com/");

Независимо от того, какой фрагмент кода я использую, экземпляр браузера, который запускаетсявсегда не может обработать сгенерированный контент, браузер запрашивает у меня действие по выполнению контента нераспознанного типа MIME, как если бы расширение было неправильно настроено.

Любые идеи о том, что я могу делать неправильно?

Заранее спасибо,

Редактировать : Ссылка на сообщение группы пользователей Selenium .

Ответы [ 3 ]

1 голос
/ 08 февраля 2012

Надеюсь, это поможет вам:

public class Wap {

public static void main (String[] args) throws IOException{ 

FirefoxProfile profile = new FirefoxProfile();
String baseURL;
profile.addExtension(new File("C:\\Users\\Pandu\\Desktop\\WAP\\modify_headers-0.7.1.1-fx.xpi"));

profile.setPreference("modifyheaders.config.active", true);
profile.setPreference("modifyheaders.config.alwaysOn", true);
profile.setPreference("modifyheaders.headers.count", 2);
profile.setPreference("modifyheaders.headers.action0", "Add");
profile.setPreference("modifyheaders.headers.name0", "X-Nokia-msisdn");
profile.setPreference("modifyheaders.headers.value0", "123456789");
profile.setPreference("modifyheaders.headers.enabled0", true);
profile.setPreference("modifyheaders.headers.action1", "Add");
profile.setPreference("modifyheaders.headers.name1", "x-sec-pass");
profile.setPreference("modifyheaders.headers.value1", "sdp123");
profile.setPreference("modifyheaders.headers.enabled1", true);


    Logger Log = Logger.getLogger(WebDriver.class.getName());

    WebDriver driver = new FirefoxDriver(profile);
    try{
driver.get("http://www.google.com");

        driver.findElement(By.linkText("Telugu")).click();
1 голос
/ 31 января 2013

Вы должны убедиться, что вы добавили плагин для браузера в качестве DeploymentItem в ваш файл testsettings.Некоторые примеры (в этом мы добавили Firebug):

  <Deployment>
    <DeploymentItem filename="Selenium\firebug@software.joehewitt.com.xpi" />
    <DeploymentItem filename="packages\Castle.Core.3.1.0\lib\net40-client\Castle.Core.dll" />
    <DeploymentItem filename="Selenium\IEDriverServer.exe" />
    <DeploymentItem filename="Selenium\chromedriver.exe" />
    <DeploymentItem filename="Selenium\skipcerterror@foudil.fr.xpi" />
  </Deployment>

Затем вам нужно будет создать профиль, похожий на этот:AddExtension, он должен быть доступен в вашем драйвере селена.Надеюсь, это поможет.

1 голос
/ 05 февраля 2012

Попробуйте начать с пустого профиля и добавить расширения / конфигурации во время выполнения:

public WebDriver getDriver() {
    FirefoxProfile profile = new FirefoxProfile();

    // add any custom firefox configurations...
    profile.setPreference("general.useragent.override", "some UA string");
    profile.setPreference("javascript.options.showInConsole", true);
    profile.setPreference("dom.max_script_run_time", 0);

    // might have to uninstall, search for *.xpi, then reinstall, then search 
    // again and compare to find the location on your system
    // ...you should probably copy this into your selenium resources directory!
    File modifyHeadersXpi = new File("/home/joecoder/.mozilla/firefox/dll8peh9.default/extensions/{b749fc7c-e949-447f-926c-3f4eed6accfe}.xpi");
    if (modifyHeadersXpi.exists()) {
        try {
            profile.addExtension(modifyHeadersXpi);
            profile.setPreference("modifyheaders.config.active", true);
            profile.setPreference("modifyheaders.config.openNewTab", true);
            profile.setPreference("modifyheaders.config.migrated", true);
            profile.setPreference("modifyheaders.autocomplete.name.defaults", 
                    "[\"Accept\",\"Cache-Control\",\"Cookie\",\"Content-Length\",\"Content-Type\",\"Date\",\"Host\",\"Pragma\",\"Referer\",\"User-Agent\",\"Via\",\"X-Requested-With\",\"X-Forwarded-For\",\"X-Do-Not-Track\"]");
        }
        catch (IOException e) { /* uh oh */ }
    }
    return new FirefoxDriver(profile);
}
...