Webdriver selenium python status code

Как получить код состояния с помощью selenium.py (код Python)

Я пишу selenium script на python, но я думаю, что не вижу никакой информации о: Как получить код статуса http из selenium Python code. Или я чего-то не хватает. Если кто-нибудь нашел это, пожалуйста, не стесняйтесь публиковать сообщения.

9 ответов

Это не возможно.

  • Selenium — это инструмент эмуляции браузера, не обязательно инструмент для тестирования.
  • Selenium выполняет много GET и POST во время процесса рендеринга страницы, и добавление интерфейса для этого осложнит API таким образом, чтобы авторы сопротивлялись.

У нас остались хаки вроде:

  • Ищите информацию об ошибках в возвращаемом HTML.
  • Используйте другой инструмент вместо запросов (но посмотрите на недостатки этого подхода в ответе @Zeinab.

Я занимаюсь серфингом в сети около 3 часов, и я не нашел ни единого способа сделать это с помощью веб-драйвера. Я никогда не работал с селеном напрямую. Единственное предложение, которое появилось у меня в голове, это использовать «запросы» модуля следующим образом:

import requests from selenium import webdriver driver = webdriver.get("url") r = requests.get("url") print r.status_code 

Полное руководство по использованию запросов здесь, и вы можете установить модуль с помощью команды pip install requests .

Но есть проблема, которая может не всегда происходить, но вы должны сосредоточить внимание на ответе и ответе ответа драйвера не одинаковыми; поэтому вы просто получаете код статуса запроса и, если ответные URL нестабильны, это, вероятно, приводит к неправильным результатам.

Читайте также:  Sending php variable header

Так проблематично. Помимо всех этих проблем, вы получаете запрос дважды, и, кроме того, его нельзя использовать, если вы планируете использовать URL Selenium GET или POST.

К сожалению, некоторые веб-сайты предоставляют разные коды ответов для этих разных модулей. Что нужно знать (попробуйте подделать пользовательский агент, если вы полагаетесь на запросы кодов состояния, используемых в Selenium)

На самом деле, это хорошая идея использовать HTTP-запрос и определить, является ли URL действительным или нет.

У меня нет большого опыта работы с python. У меня есть более подробный пример java здесь:

Идея состоит в том, чтобы включить ведение журнала производительности. Это запускает «Network.enable» на хромированном краю. Затем запустите записи журнала производительности и проанализируйте их для сообщения «Network.responseReceived».

 from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities # enable browser logging d = DesiredCapabilities.CHROME d['loggingPrefs'] = < 'performance':'ALL' >driver = webdriver.Chrome(executable_path="c:\\windows\\chromedriver.exe", service_args=["--verbose", "--log-path=D:\\temp3\\chromedriverxx.log"], desired_capabilities=d) driver.get('https://api.ipify.org/?format=text') print(driver.title) print(driver.page_source) performance_log = driver.get_log('performance') print (str(performance_log).strip('[]')) for entry in driver.get_log('performance'): print (entry) 

Выход будет содержать «Network.responseReceived» для вашего URL-адреса, другие запросы, выполняемые загрузкой страницы, или перенаправление URL-адресов. Все, что вам нужно сделать, это проанализировать записи журнала.

',"headersText":"HTTP/1.1 200 OK\\r\\nServer: Cowboy\\r\\nConnection: keep-alive\\r\\nContent-Type: text/plain\\r\\nDate: Wed, 12 Oct 2016 06:15:47 GMT\\r\\nContent-Length:13\\r\\nVia:1.1vegur\\r\\n\\r\\n","mimeType":"text/plain","protocol":"http/1.1","remoteIPAddress":"54.197.246.207","remotePort":443,"requestHeaders":,"requestHeadersText":"GET /?format=text HTTP/1.1\\r\\nHost: api.ipify.org\\r\\nConnection: keep-alive\\r\\nUpgrade-Insecure-Requests: 1\\r\\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\\r\\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\\r\\nAccept-Encoding: gzip, deflate, sdch, br\\r\\nAccept-Language: en-GB,en-US;q=0.8,en;q=0.6\\r\\n\\r\\n","securityDetails":,"cipher":"AES_128_GCM","keyExchange":"ECDHE_RSA","protocol":"TLS 1.2","signedCertificateTimestampList":[]>,"securityState":"secure","status":200,"statusText":"OK","timing":,"url":"https://api.ipify.org/?format=text">,"timestamp":78247.242716,"type":"Document">>,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, >,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, >>,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, >,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, >,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, >,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, >,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'>, ,"loaderId":"9488.1","request":,"initialPriority":"High","method":"GET","mixedContentType":"none","url":"https://api.ipify.org/favicon.ico">,"requestId":"9488.2","timestamp":78247.280131,"type":"Other","wallTime":1476252948.11805>>,"webview":"6e8a3b1d-e5aa-40fb-a695-280cbb0ee420">'> 

и получить «статус»: 200 из ответа json. Вы также можете проанализировать ответные заголовки.

Источник

How to get status code by using selenium.py (python code)?

Selenium is a popular automation testing framework widely used for web application testing. It provides a way to interact with web pages and perform various actions on them, such as clicking buttons, entering text, and extracting data. While using Selenium, it’s often necessary to check the status code of a page to verify whether it has loaded successfully or not. In this article, we’ll show you how to retrieve the status code using Selenium in Python.

Method 1: Using the WebDriver API

To get the status code of a webpage using Selenium WebDriver API in Python, you can follow these steps:

from selenium import webdriver
driver.get("https://www.example.com")
status_code = driver.execute_script("return window.performance.getEntries()[0].response.status")
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.example.com") status_code = driver.execute_script("return window.performance.getEntries()[0].response.status") driver.quit()
  • Step 1: Import the webdriver module from the selenium library.
  • Step 2: Create a new instance of the webdriver using the Chrome() method.
  • Step 3: Navigate to the webpage using the get() method.
  • Step 4: Use the execute_script() method to execute JavaScript code to get the status code of the webpage. The window.performance.getEntries()[0].response.status code retrieves the status code of the first resource loaded on the page.
  • Step 5: Close the webdriver using the quit() method.

Note: You can change the URL in Step 3 to the webpage you want to get the status code for.

Method 2: Using the Requests library

To get the status code using the Requests library in Python, you can follow these steps:

status_code = response.status_code
import requests url = 'https://www.example.com' response = requests.get(url) status_code = response.status_code print(status_code)

This code will send a GET request to the URL and print the status code to the console. You can replace the URL with the one you want to get the status code for.

Note: The Requests library is not used with Selenium. It is a separate library used for making HTTP requests. Selenium is used for automating web browsers.

Источник

bcarroll / ChromeWebDriver.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

«»»
Implementation of the Selenium Chrome WebDriver
with HTTP Response data included via the ChromeDriver performance logging capability
https://sites.google.com/a/chromium.org/chromedriver/logging/performance-log
The ChromeWebDriver response attribute(s) contain a dict with information about the response
«connectionId»: [Integer],
«connectionReused»: [Boolean],
«encodedDataLength»: [Integer],
«fromDiskCache»: [Boolean],
«fromServiceWorker»: [Boolean],
«headers»: [dict], # HTTP Headers as a dict
«headersText»: [String], # HTTP Headers as text
«mimeType»: [String],
«protocol»: [String],
«remoteIPAddress»: [String],
«remotePort»: [Integer],
«requestHeaders»: [dict],
«requestHeadersText»: [String],
«securityDetails»: [dict], # TLS/SSL related information
«securityState»: [String],
«status»: [Integer], # HTTP Status Code of the Response
«statusText»: [String],
«timing»: [dict],
«url»: [String]
>
Example:
from ChromeWebDriver import ChromeWebDriver
browser = ChromeWebDriver(‘https://github.com’, headless=False)
print(browser.response[«status»]) # prints the HTTP status code of the response (for the url in the class initialization)
for response in browser.responses: # the responses attribute contains a list of dicts containing all responses received (css, js, etc.)
print(response) # prints a dict containing data for each response
«»»
import json
from selenium import webdriver
from selenium . webdriver . common . desired_capabilities import DesiredCapabilities
class ChromeWebDriver ():
def __init__ ( self , url , headless = False , autoclose = True ):
self . url = url # URL to fetch
self . options = webdriver . ChromeOptions ()
self . options . headless = headless
self . desired_capabilities = DesiredCapabilities . CHROME
self . desired_capabilities [ ‘loggingPrefs’ ] =
self . driver = webdriver . Chrome ( options = self . options , desired_capabilities = self . desired_capabilities )
self . driver . get ( url ) # get the requested URL
self . responses = [] # list to store each response
perfLog = self . driver . get_log ( ‘performance’ )
for logIndex in range ( 0 , len ( perfLog )): # Parse the Chrome Performance logs
logMessage = json . loads ( perfLog [ logIndex ][ «message» ])[ «message» ]
if logMessage [ «method» ] == «Network.responseReceived» : # Filter out HTTP responses
self . responses . append ( logMessage [ «params» ][ «response» ]) # append each response to self.responses
if logMessage [ «params» ][ «response» ][ «url» ] == self . url : # create instance attributes containing the response call for self.url
self . response = logMessage [ «params» ][ «response» ]
self . driver . close ()

Источник

Оцените статью