selenium通过performance log获取状态码,Content-Type,以及重定向路径

这篇具有很好参考价值的文章主要介绍了selenium通过performance log获取状态码,Content-Type,以及重定向路径。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

selenium的官方不提供获取状态码,Content-Type,以及重定向路径的方法,并且官方说这些功能将来也不会有。java - How to get HTTP Response Code using Selenium WebDriver - Stack Overflow

非官方的方法大概有下面几种

1.通过requests重新请求一遍url,获取response里面的状态码

2.通过中间代理服务器来获取,比如selenium-wire,selenium-wire里面内建了一个代理服务器,通过代理服务器可以获取各个请求的状态码

3.通过分析chrome的performance log来获取状态码以及重定向路径

1的方法会多访问一遍网络,并且不能支持mata或js的重定向。2的方法只访问一次网络,但同样不能支持mata或js的重定向,只有3的方法只访问一次网络可以获取所有的状态。

并且1的方法在python环境上打开一些https网站还有如下bug

ssl.SSLError: [SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled (_ssl.c:1131) · Issue #2653 · urllib3/urllib3 · GitHuby

 这个问题的原因是This error comes up when using OpenSSL 3 to connect to a server which does not support it. The solution is to downgrade the cryptography package in python:

  python - SSL error unsafe legacy renegotiation disabled - Stack Overflow

要么修改openssl.cnf,要么降级cryptography,要么设置ctx,根据我测试的结果只有修改cnf才能彻底解决,最简单的方法是在cnf后面加上Options = UnsafeLegacyRenegotiation

如果使用docker应该写成这样

RUN echo 'Options = UnsafeLegacyRenegotiation' >> /usr/lib/ssl/openssl.cnf

如何通过performance log来获取状态

performanceLog.py

import json

def getHeader(headers,header):
    for key,value in headers.items():
        if key.lower()==header:
            return value
    return ''
def getRedirectPath(driver):
    redirctPath=[]
    requestDic={}
    frameId=None
    for entry_json in driver.get_log('performance'):
        entry = json.loads(entry_json['message'])
        # print(entry)
        if entry['message']['method'] == 'Network.requestWillBeSent':
            if entry['message']['params']['loaderId']==entry['message']['params']['requestId'] and (frameId is None or frameId==entry['message']['params']['frameId']):
                # print(entry)
                if frameId is None:
                    frameId=entry['message']['params']['frameId']
                if entry['message']['params']['redirectHasExtraInfo']:
                    # 设置重定向前的状态
                    item=redirctPath[len(redirctPath)-1]
                    item['status']=entry['message']['params']['redirectResponse']['status']
                    item['reason']='location'
                    item['contentType']=getHeader(entry['message']['params']['redirectResponse']['headers'],'content-type')

                item={
                    'url':entry['message']['params']['request']['url'],
                    'status':'',
                    'reason':'',
                    'contentType':''
                }
                requestDic[entry['message']['params']['requestId']]=item
                redirctPath.append(item)
        elif entry['message']['method'] == 'Network.responseReceived' and entry['message']['params']['requestId'] in requestDic:
            # print(entry)
            item=requestDic[entry['message']['params']['requestId']]
            item['status']=entry['message']['params']['response']['status']
            item['contentType']=getHeader(entry['message']['params']['response']['headers'],'content-type')
        elif entry['message']['method'] == 'Page.frameRequestedNavigation' and frameId==entry['message']['params']['frameId']:
            # print(entry)
            # 设置重定向前的状态
            item=redirctPath[len(redirctPath)-1]
            item['reason']=entry['message']['params']['reason']
    return redirctPath

 后来发现一些网站不能获取contentType,原因是header需要忽略大小写,修改了一下代码。当然你自己修改代码后可以获取任何你需要的header。

各个事件的顺序大致如下

Page.frameStartedLoading
Network.requestWillBeSent
Network.responseReceived
Network.dataReceived
Page.frameNavigated
Network.requestServedFromCache
Network.loadingFinished
Network.resourceChangedPriority
Page.domContentEventFired
Network.loadingFailed
Page.loadEventFired
Page.frameStoppedLoading

注释:Page.frameScheduledNavigation已经被废弃,改成Page.frameRequestedNavigation

官方对performance log的文档很少,在网上也没有找到类似的讨论,上面的代码完全是我根据数据分析出来的,目前看来是对的,如果不对请告诉我。 

Chrome DevTools Protocol - version 1-2 - Page domain

 测试代码

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
from performanceLog import getRedirectPath

caps = DesiredCapabilities.CHROME
caps['goog:loggingPrefs'] = {'performance': 'ALL'}
options = webdriver.ChromeOptions()
# 必须是headless=new,否则download.default_directory不起作用
options.add_argument('--headless=new')
# 下面这些参数是必须的,否则可能出错
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=options,desired_capabilities=caps)

driver.get('http://localhost/redirect')
# 必须等待几秒钟,否则metaTagRefresh不起作用
time.sleep(3)

print(getRedirectPath(driver))
driver.quit()

输出结果

[{
    'url': 'http://localhost/redirect',
    'status': 302,
    'reason': 'location',
    'contentType': 'text/html; charset=utf-8'
}, {
    'url': 'http://localhost/static/index3.html',
    'status': 200,
    'reason': 'scriptInitiated',
    'contentType': 'text/html'
}, {
    'url': 'http://localhost/static/redirect.html',
    'status': 200,
    'reason': 'metaTagRefresh',
    'contentType': 'text/html'
}, {
    'url': 'http://localhost/',
    'status': 200,
    'reason': '',
    'contentType': 'text/html; charset=utf-8'
}]

可以看出这里面有3种不同类型的重定向,location的通常的重定向,后面2种用requests或者代理都无法获取。

location:response header里面的location重定向

scriptInitiated:js重定向

metaTagRefresh:meta tag重定向文章来源地址https://www.toymoban.com/news/detail-787814.html

到了这里,关于selenium通过performance log获取状态码,Content-Type,以及重定向路径的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 详解Http的Content-Type

    目录 1.概述 2.常用类型 2.1.application/x-www-form-urllencoded 2.2.application/json 3.Spring MVC支持的编码 3.1.实验 3.2.适配器 3.3.自定义适配器 HTTP(HyperText Transfer Protocol),超文本传输协议。超文本(Hypertext)是一种结构化的文本,其中包含了超链接(Hyperlink)的能力,通过超链接可以在不

    2024年02月09日
    浏览(29)
  • Http请求中的Content-Type

    前阵子公司接回了一个旧的项目,刚开始的时候没有注意看前端设置的content-type,然后与后端同事进行接口联调的时候就,有时候发现数据就是对不上,后面看了一下代码中的axios请求相关设置,才发现是自己走坑了!主要是在请求拦截和响应拦截这块的处理,请求拦截这块

    2024年02月12日
    浏览(69)
  • Http Content-type 对照表

    文件扩展名 Content-Type(Mime-Type) 文件扩展名 Content-Type(Mime-Type) .*( 二进制流,不知道下载文件类型) application/octet-stream .tif image/tiff .001 application/x-001 .301 application/x-301 .323 text/h323 .906 application/x-906 .907 drawing/907 .a11 application/x-a11 .acp audio/x-mei-aac .ai application/postscript .aif audio/aiff

    2024年02月09日
    浏览(31)
  • 前端知识~Content-Type和Accept

    Content-Type和Accept是两个HTTP标头(HTTP headers),用于在HTTP请求和响应之间传递有关请求的数据类型和响应的首选内容类型的信息。这两个标头在HTTP通信中起着关键的作用。 Content-Type: Content-Type 是HTTP请求头或响应头的一部分,用于指示HTTP消息主体(请求或响应体)的媒体类

    2024年02月10日
    浏览(28)
  • content-type几种常见类型区别

    Content-Type叫做MIME(mediaType)类型,使用Content-Type来表示请求和响应中的媒体类型信息。如果是请求头,它用来告诉服务端如何处理请求的数据,如果是响应头,它用来告诉客户端(一般是浏览器)如何解析响应的数据。下面我们来介绍下常用的几种类型! 1.application/x-www-form

    2024年02月03日
    浏览(35)
  • 如何在 Postman 中设置 Content-Type?

    在使用  Postman  进行 API 测试时,有时需要设置请求的 Content-Type。本文将介绍如何在 Postman 中设置 Content-Type。想要学习更多关于 Postman 的知识,可访问 Postman 中文文档。 1、首先,打开 Postman 工具并创建一个新的请求接口。输入请求地址,例如  https://api.example.com/user 。 2、

    2024年02月08日
    浏览(39)
  • HTTP的Content-type 和 responseType

    后端返回字节流,前端进行图片下载时遇到了问题,定位花了不少时间,本文再次记录梳理下  XMLHttpRequest本身支持responseType 允许我们手动的设置返回数据的类型 \\\'\\\' responseType 为空字符串时,采用默认类型 DOMString,与设置为 text 相同。 arraybuffer response 是一个包含二进制数据的

    2024年01月22日
    浏览(28)
  • Nginx:设置响应header的content-type

    Nginx通常根据/etc/nginx/mime.types文件中类型设置content-type 有时需要根据实际需要指定content-type,比如对于下载,如果按照mime.types里面的定义: image/jpeg                            jpeg jpg; 那么当下载图片时,浏览器会在窗口内直接显示图片,而不是另存为文件 。 通过设置

    2024年02月12日
    浏览(27)
  • 浏览器响应数据类型(Content-Type)详解

    浏览器要显示内容,首先需要判断响应消息中的数据属于哪种类型。Web 可以处理的数据包括文字、图像、声音、视频等多种类型,每种数据的显示方法都不同,因此必须先要知道返回了什么类型的数据,否则无法正确显示。 这时,我们需要一些信息才能判断数据类型,原则

    2024年02月11日
    浏览(40)
  • 关于openfeign调用时content-type的问题

    今天在A服务使用openfeign调用B服务的时候,发现经常会偶发性报错。错误如下: 情况为偶发,很让人头疼。 两个接口如下: A服务接口: delayReasonApi.test(student); 就是使用openfeign调用B服务的接口。 B服务接口: 因为A服务的接口是一个文件上传的接口,所以前端请求头中使用的

    2024年02月12日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包