Selenium как запустить браузер с расширением
Селен + Python Настройка параметров браузера Chrome
1. Справочная информация
При использовании технологии рендеринга в браузере selenium для сканирования информации на сайте по умолчанию это обычный браузер с чистым Chrome, и мы обычно добавляем некоторые плагины, расширения, агенты и другие приложения при использовании браузера. Соответственно, когда мы используем браузер Chrome для сканирования веб-сайта, нам может потребоваться выполнить специальную настройку для этого хрома, чтобы он соответствовал поведению сканера.
Обычно используемые поведения:
Запретить загрузку изображений и видео. Увеличьте скорость загрузки веб-страниц.
Добавить прокси: технология защиты от лазания, используемая для доступа к определенным страницам через стену или реагирования на ограничения частоты доступа по IP.
Использовать мобильную голову: зайдите на мобильный сайт, как правило, технология против скалолазания на этом сайте относительно слаба.
Добавить расширения: функционирует как обычный браузер.
Установите код: ответьте на китайскую станцию, чтобы предотвратить искажение символов.
Блокировать выполнение JavaScript.
………
2. Окружающая среда
python 3.6.1
Система: win7
IDE:pycharm
Установили браузер Chrome
Хромированный драйвер настроен
selenium 3.7.0
ChromeOptions - это класс, который настраивает запуск Chrome как атрибут. С помощью этого класса мы можем настроить следующие параметры для Chrome (эту часть можно увидеть через исходный код селена):
Установить местоположение двоичного файла Chrome (binary_location)
Добавить параметры запуска (add_argument)
Добавить приложение расширения (add_extension, add_encoded_extension)
Добавить параметры экспериментальной настройки (add_experimental_option)
Установить адрес отладчика (debugger_address)
4. Общая конфигурация
4.1 Установить формат кодировки
4.2 Моделирование мобильных устройств
4.3 Запретить загрузку изображений
Это может увеличить скорость сканирования без загрузки изображений.
4.4 Добавить агента
Добавьте прокси-сервер для искателя селена. В этом месте особенно важно отметить, что при выборе прокси-сервера старайтесь выбирать статический IP-адрес, чтобы повысить стабильность сканирования. Потому что если вы выбираете селен в качестве сканера, это означает, что антискользящая способность веб-сайта относительно высока (в противном случае он находится прямо на скрапе), и у него более высокий контроль согласованности между веб-страницами, файлами cookie и статусом пользователя. Если вы используете динамический анонимный IP, время выживания каждого IP будет очень коротким (1 ~ 3 минуты).
4.5 Настройки параметров браузера
Обычно Selenium открывает чистый браузер без расширений, но иногда мы хотим установить в браузере некоторые настройки, например, установить значение по умолчанию для параметра flash, чтобы всегда разрешать глобальное удаление файлов cookie, очистку кешей и тому подобное.
Для достижения этой цели существует способ мышления. В качестве примера ниже приводится браузер Chrome:
Когда запускается искатель селена, сначала откройте окно, введите в адресную строку: chrome: // settings / content или chrome: // settings / privacy, а затем программу, как в обычном веб-приложении. Аналогично, установите и сохраните.
Напишите описание изображения здесь
4.6. Добавить приложение для расширения браузера
Обычно Selenium открывает чистый браузер без расширений, но иногда нам нужно использовать некоторые плагины для обхода данных, такие как класс синтаксического анализа xpath helper, класс перевода и получение дополнительной информации (продажи). Итак, как мы можем добавить некоторые плагины, которые нам нужны, когда мы запускаем chromedriver?
Ниже приведен пример загрузки подключаемого модуля Xpath Helper в Chrome:
4.6.2 Заполните путь к плагину в коде
4.6.3 Отображение результатов
Напишите описание изображения здесь
4.6.4. Примечания
5. Другие параметры
5.1 Команды адресной строки Chrome
Введите следующую команду в адресной строке браузера Chrome, и соответствующий результат будет возвращен. Эти команды включают в себя просмотр состояния памяти, состояния браузера, состояния сети, состояния DNS-сервера, кеша подключаемых модулей и т. Д. Однако следует отметить, что эти команды постоянно меняются, поэтому их не обязательно легко использовать.
about: version - отображает текущую версию
about: memory - отображает использование памяти локальным браузером
about: plugins-отображает установленные плагины
about: история отображения гистограмм
about: dns-отображает статус DNS
about: кэш-страница отображения кеша
about: gpu-есть ли аппаратное ускорение
О файле: flags-Open Некоторые плагины // После использования что-то всплывает: «Пожалуйста, будьте осторожны, эти эксперименты могут быть рискованными», интересно, если я испорчу свою конфигурацию!
chrome: // extensions / -Просмотреть установленные расширения
5.2 Практические параметры Chrome
Некоторые другие практические параметры о Chrome и краткие китайские инструкции, способ использования такой же, как и выше 4.5.4, конечно, его также можно использовать в оболочке.
While running selenium, I need to load a chrome extension from the web store. In my research, I only found how to load an extension from the local machine.
Is it possible for selenium to load an extension from the Web Store?
An option is to use java to download crx file from webstore everytime you run the test scripts and then load the downloaded script into chromeoptions. There are many options to download file from internet in Java. Will the approach acceptable in your case?
yes, even downloading the extension from store and then installing it will also do. But I am not sure if we can download CRX file ? Do we have download URLs available ?
I don't see any of the proposed solutions offering a way to do this without human interaction upfront - i.e. manually loading the crx file. All but mine that is - mine offers the ability to download the crx file programmatically. we're not talking about using load-extension or add.argument options before starting chrome. nuff said.
7 Answers 7
I am not sure why you are particular about downloading from Webstore and then install into Chrome.
I found some steps to download chrome extensions:
-With a computer connected to the internet, install the extension from the extension page: https://chrome.google.com/webstore/detail/
-Navigate to the extension source code. In XP this is found at: C:\Documents and Settings\\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
-You should see a version folder (ie. "0.0.21_0"). Copy this folder and move it on the machine you want to install on.
-Open up chrome on the disconnected machine and go to Wrench -> Tools -> Extensions
-Click the + next to Developer mode to display the developer options
-Click 'Pack extension. ' and choose the version folder as the root directory. Leave the private key file blank. This will create a .crx file in the version folder along with a private key as if you were the developer.
3- and replacing ~~~~ with the extension ID. You’ll be prompted to save a CRX file. Drag this file to a Chrome window and proceed with installation.
Finally, use the downloaded .crx file in ChromeOptions to load the extension
I am currently using Selenium to run instances of Chrome to test web pages. Each time my script runs, a clean instance of Chrome starts up (clean of extensions, bookmarks, browsing history, etc). I was wondering if it's possible to run my script with Chrome extensions. I've tried searching for a Python example, but nothing came up when I googled this.
6 Answers 6
You should use Chrome WebDriver options to set a list of extensions to load. Here's an example:
Hope that helps.
Hi, I tested your code. But things may seem deprecated. I am getting a traceback about the directory of the extension IsADirectoryError [Error 21] . I just want to know how to write the full path to the extension. What I have here is path/to/XXXXXXXXXXXXXXXXX/1.2.345 should I put this version number in the path??
I hope you help. I have used this answer to get the path to the extension so do you have an Idea why I am facing this error? IsADirectoryError [Error 21] . Thanks in advance.
The leading answer didn't work for me because I didn't realize you had to point the webdriver options toward a .zip file.
I.e. chrome_options.add_extension('path_to_extension_dir') doesn't work.
You need: chrome_options.add_extension('path_to_extension_dir.zip')
After figuring that out and reading a couple posts on how to create the zip file via the command line and load it into selenium , the only way it worked for me was to zip my extension files within the same python script. This actually turned out to be a nice way for automatically updating any changes you might have made to your extension:
Unfortunately it is not working for me, can you provide an example of the values that need to go into ext_dir = 'extension' ext_file = 'extension.zip'
This is because the selenium expects the packed extensions as the extension argument which will be with .crx extension.
I already had the extension in my chrome. Below are the steps I followed to pack the existing extension,
- Click on your extension 'details'. In my Chrome version, it was on right top click (3 dots) -> 'More tools' -> 'Extensions'.
- Have the developer mode enabled in your chrome
- Click 'Pack extension' (As shown above) and pack it.
- This will get stored in the extensions location. For me it was on /home/user/.config/google-chrome/Default/Extensions/fdjsidgdhskifcclfjowijfwidksdj/2.3.4_22.crx
That's it, you can configure the extension in your selenium as argument.
NOTE: You can also find the 'fdjsidgdhskifcclfjowijfwidksdj' id in the extensions url as query param
If you wanna import any chrome extension in your selenium python scrip
Put your extension.crx.crx file in the same folder as your code or give the path
you can copy-paste this code and just change the file crx.crx name
if this code is throwing an error maybe this will solve it
I also needed to add an extention to chrome while using selenium. What I did was first open the browser using selenium then add extention to the browser in the normal way like you would do in google chrome.
This works if you are okay with some manual steps. It's non-ideal for those trying to fully automate whatever it is they are doing in selenium.
An alternative way is to use the unpacked folder method. I found the crx and zip method did not work at all on Selenium Grid. In this method, you need to copy the extension from the user data in a Chrome version where you have already manually installed it, the long ID made up of loads of letters like pehaalcefcjfccdpbckoablngfkfgfgj, to the user data directory of the Selenium-controlled Chrome (which you can choose at runtime using the first line of this code, and it will get populated automatically). It should be in the same equivalent directory (which is Extensions). The path must take you all the way to the directory where there is a manifest.json, hence in this example '1.1.0'
WebDriver does not make the distinction between windows and tabs. If your site opens a new tab or window, Selenium will let you work with it using a window handle. Each window has a unique identifier which remains persistent in a single session. You can get the window handle of the current window by using:
Switching windows or tabs
Clicking a link which opens in a new window will focus the new window or tab on screen, but WebDriver will not know which window the Operating System considers active. To work with the new window you will need to switch to it. If you have only two tabs or windows open, and you know which window you start with, by the process of elimination you can loop over both windows or tabs that WebDriver can see, and switch to the one which is not the original.
However, Selenium 4 provides a new api NewWindow which creates a new tab (or) new window and automatically switches to it.
Create new window (or) new tab and switch
Creates a new window (or) tab and will focus the new window or tab on screen. You don’t need to switch to work with the new window (or) tab. If you have more than two windows (or) tabs opened other than the new window, you can loop over both windows or tabs that WebDriver can see, and switch to the one which is not the original.
Note: This feature works with Selenium 4 and later versions.
Closing a window or tab
When you are finished with a window or tab and it is not the last window or tab open in your browser, you should close it and switch back to the window you were using previously. Assuming you followed the code sample in the previous section you will have the previous window handle stored in a variable. Put this together and you will get:
Forgetting to switch back to another window handle after closing a window will leave WebDriver executing on the now closed page, and will trigger a No Such Window Exception. You must switch back to a valid window handle in order to continue execution.
Quitting the browser at the end of a session
When you are finished with the browser session you should call quit, instead of close:
- Quit will:
- Close all the windows and tabs associated with that WebDriver session
- Close the browser process
- Close the background driver process
- Notify Selenium Grid that the browser is no longer in use so it can be used by another session (if you are using Selenium Grid)
Failure to call quit will leave extra background processes and ports running on your machine which could cause you problems later.
Some test frameworks offer methods and annotations which you can hook into to tear down at the end of a test.
If not running WebDriver in a test context, you may consider using try / finally which is offered by most languages so that an exception will still clean up the WebDriver session.
Python’s WebDriver now supports the python context manager, which when using the with keyword can automatically quit the driver at the end of execution.
Window management
Screen resolution can impact how your web application renders, so WebDriver provides mechanisms for moving and resizing the browser window.
Once you have Selenium installed and Drivers installed, you’re ready to write Selenium code.
Eight Basic Components
Everything Selenium does is send the browser commands to do something or send requests for information. Most of what you’ll do with Selenium is a combination of these basic commands:
1. Start the session
For more details on starting a session read our documentation on opening and closing a browser
2. Take action on browser
In this example we are navigating to a web page.
3. Request browser information
4. Establish Waiting Strategy
Synchronizing the code with the current state of the browser is one of the biggest challenges with Selenium, and doing it well is an advanced topic.
Essentially you want to make sure that the element is on the page before you attempt to locate it and the element is in an interactable state before you attempt to interact with it.
An implicit wait is rarely the best solution, but it’s the easiest to demonstrate here, so we’ll use it as a placeholder.
5. Find an element
The majority of commands in most Selenium sessions are element related, and you can’t interact with one without first finding an element
6. Take action on element
There are only a handful of actions to take on an element, but you will use them frequently.
7. Request element information
Elements store a lot of information that can be requested. Notice that we need to relocate the search box because the DOM has changed since we first located it.
8. End the session
This ends the driver process, which by default closes the browser as well. No more commands can be sent to this driver instance.
Putting everything together
Let’s combine these 8 things into a complete script.
Follow the link at the bottom of the tab to see an example of the code as it would be executed with a test runner instead of a standalone file.
Next Steps
Take what you’ve learned and build out your Selenium code.
As you find more functionality that you need, read up on the rest of our WebDriver documentation.
Selenium Level Sponsors
Support the Selenium Project
Want to support the Selenium project? Learn more or view the full list of sponsors.
Читайте также: