
Estende os bindings Python do Selenium para dar a você a capacidade de inspecionar as requisições feitas pelo navegador.
Selenium Wire não está mais sendo mantido. Obrigado pelo seu apoio e por todas as suas contribuições.
Selenium Wire estende os bindings Python do Selenium <https://www.selenium.dev/documentation/en/>_ para dar acesso às requisições subjacentes feitas pelo navegador. Você escreve seu código da mesma forma que faz com Selenium, mas obtém APIs extras para inspecionar requisições e respostas e fazer alterações nelas em tempo real.
.. image:: https://github.com/wkeeling/selenium-wire/workflows/build/badge.svg :target: https://github.com/wkeeling/selenium-wire/actions
.. image:: https://codecov.io/gh/wkeeling/selenium-wire/branch/master/graph/badge.svg :target: https://codecov.io/gh/wkeeling/selenium-wire
.. image:: https://img.shields.io/badge/python-3.7%2C%203.8%2C%203.9%2C%203.10-blue.svg :target: https://pypi.python.org/pypi/selenium-wire
.. image:: https://img.shields.io/pypi/v/selenium-wire.svg :target: https://pypi.python.org/pypi/selenium-wire
.. image:: https://img.shields.io/pypi/l/selenium-wire.svg :target: https://pypi.python.org/pypi/selenium-wire
.. image:: https://pepy.tech/badge/selenium-wire/month :target: https://pepy.tech/project/selenium-wire
Exemplo Simples~~~~~~~~~~~~~~
.. code:: python
from seleniumwire import webdriver # Import from seleniumwire
# Create a new instance of the Chrome driver
driver = webdriver.Chrome()
# Go to the Google home page
driver.get('https://www.google.com')
# Access requests via the `requests` attribute
for request in driver.requests:
if request.response:
print(
request.url,
request.response.status_code,
request.response.headers['Content-Type']
)
Prints:
.. code:: bash
https://www.google.com/ 200 text/html; charset=UTF-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png 200 image/png
https://consent.google.com/status?continue=https://www.google.com&pc=s×tamp=1531511954&gl=GB 204 text/html; charset=utf-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png 200 image/png
https://ssl.gstatic.com/gb/images/i2_2ec824b0.png 200 image/png
https://www.google.com/gen_204?s=webaft&t=aft&atyp=csi&ei=kgRJW7DBONKTlwTK77wQ&rt=wsrt.366,aft.58,prt.58 204 text/html; charset=UTF-8
...
Features
* Pure Python, user-friendly API
* HTTP and HTTPS requests captured
* Intercept requests and responses
* Modify headers, parameters, body content on the fly
* Capture websocket messages
* HAR format supported
* Proxy server support
Compatibilty
Table of Contents
- `Instalação`_
* `Configuração do Navegador`_
* `OpenSSL`_
- `Criação do Webdriver`_
- `Acessando Requisições`_
- `Objetos de Requisição`_
- `Objetos de Resposta`_
- `Interceptando Requisições e Respostas`_
* `Exemplo: Adicionar um cabeçalho de requisição`_
* `Exemplo: Substituir um cabeçalho de requisição existente`_
* `Exemplo: Adicionar um cabeçalho de resposta`_
* `Exemplo: Adicionar um parâmetro de requisição`_
* `Exemplo: Atualizar JSON no corpo de uma requisição POST`_
* `Exemplo: Autenticação básica`_
* `Exemplo: Bloquear uma requisição`_
* `Exemplo: Simular uma resposta`_
* `Remover um interceptador`_
- `Limitando a Captura de Requisições`_
- `Armazenamento de Requisições`_
* `Armazenamento em Memória`_
- `Proxies`_
* `SOCKS`_
* `Alternando Dinamicamente`_
- `Detecção de Bot`_
- `Certificados`_
* `Usando Seu Próprio Certificado`_
- `Todas as Opções`_
- `Licença`_
Instalação~~~~~~~~~~~~
Install using pip:
.. code:: bash
pip install selenium-wire
If you get an error about not being able to build cryptography you may be running an old version of pip. Try upgrading pip with ``python -m pip install --upgrade pip`` and then re-run the above command.
Browser Setup
-------------
No specific configuration should be necessary except to ensure that you have downloaded the relevent webdriver executable for your browser and placed it somewhere on your system PATH.
- `Download <https://sites.google.com/chromium.org/driver/>`__ webdriver for Chrome
- `Download <https://github.com/mozilla/geckodriver/>`__ webdriver for Firefox
- `Download <https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/>`__ webdriver for Edge
OpenSSL
-------
Selenium Wire requires OpenSSL for decrypting HTTPS requests. This is probably already installed on your system (you can check by running ``openssl version`` on the command line). If it's not installed you can install it with:
**Linux**
.. code:: bash
# For apt based Linux systems
sudo apt install openssl
# For RPM based Linux systems
sudo yum install openssl
# For Linux alpine
sudo apk add openssl
**MacOS**
.. code:: bash
brew install openssl
**Windows**
No installation is required.
Creating the Webdriver
Certifique-se de importar webdriver do pacote seleniumwire:
.. code:: python
from seleniumwire import webdriver
Em seguida, basta instanciar o webdriver como faria se estivesse usando o Selenium diretamente. Você pode passar quaisquer capacidades desejadas ou opções específicas do navegador - como o caminho do executável, modo headless etc. O Selenium Wire também tem opções próprias_ que podem ser passadas no atributo seleniumwire_options.
.. code:: python
# Create the driver with no options (use defaults)
driver = webdriver.Chrome()
# Or create using browser specific options and/or seleniumwire_options options
driver = webdriver.Chrome(
options = webdriver.ChromeOptions(...),
seleniumwire_options={...}
)
.. _opções próprias: #all-options
Observe que, para subpacotes do webdriver, você deve continuar importando-os diretamente do selenium. Por exemplo, para importar WebDriverWait:
.. code:: python
# Sub-packages of webdriver must still be imported from `selenium` itself
from selenium.webdriver.support.ui import WebDriverWait
Webdriver Remoto
O Selenium Wire tem suporte limitado para usar o cliente webdriver remoto. Ao criar uma instância do webdriver remoto, você precisa especificar o hostname ou endereço IP da máquina (ou contêiner) que está executando o Selenium Wire. Isso permite que a instância remota se comunique de volta com o Selenium Wire com suas solicitações e respostas.
.. code:: python
options = {
'addr': 'hostname_or_ip' # Address of the machine running Selenium Wire. Explicitly use 127.0.0.1 rather than localhost if remote session is running locally.
}
driver = webdriver.Remote(
command_executor='http://www.example.com',
seleniumwire_options=options
)
Se a máquina que executa o navegador precisar usar um endereço diferente para falar com a máquina que executa o Selenium Wire, você precisará configurar o navegador manualmente. Esta issue <https://github.com/wkeeling/selenium-wire/issues/220>_ entra em mais detalhes.
Acessando Requisições~~~~~~~~~~~~~~~~~~
Selenium Wire captures all HTTP/HTTPS traffic made by the browser [1]_. The following attributes provide access to requests and responses.
driver.requests
The list of captured requests in chronological order.
driver.last_request
Convenience attribute for retrieving the most recently captured request. This is more efficient than using driver.requests[-1].