【问题标题】:BrowserMob Proxy Python - How to get response body?BrowserMob 代理 Python - 如何获取响应正文?
【发布时间】:2018-11-06 02:38:57
【问题描述】:

我需要使用 Selenium Chrome 驱动程序和 browsermob 代理获取 POST 请求的响应正文内容。目前,当我阅读它时,此内容不包含在我的文件 HAR 输出中,尽管我可以在浏览器网络流量中看到响应。我怎样才能让它捕获响应流量? (抱歉,刚接触编程,看不到太多 BMP 的 python 文档)

server.start() 代理 = server.create_proxy() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) 驱动程序 = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=chrome_options) proxy.new_har("req", options={'captureHeaders': True,'captureContent':True}) driver.get('https://www.example.com/something') result_har = json.dumps(proxy.har, ensure_ascii=False) 使用 open("haroutput.har", "w") 作为 harfile: harfile.write(result_har) server.stop() driver.quit()

【问题讨论】:

    标签: python selenium selenium-chromedriver browsermob


    【解决方案1】:

    您可以通过proxy.har['log']['entries']中的同名键获取请求和响应。回复的内容在entry['response']['content']

    但在你必须将'captureContent':True 添加到proxy.new_har 调用的option 字典之前。

    例子:

    from browsermobproxy import Server
    
    server = Server("./bin/browsermob-proxy")
    
    server.start()
    proxy = server.create_proxy()
    
    from selenium import webdriver
    co = webdriver.ChromeOptions()
    co.add_argument('--proxy-server={host}:{port}'.format(host='localhost', port=proxy.port))
    
    driver = webdriver.Chrome(executable_path="chromedriver", chrome_options=co)
    
    proxy.new_har('req',options={'captureHeaders': True,'captureContent':True})
    
    driver.get(url)
    proxy.har  # returns a HAR
    
    for ent in proxy.har['log']['entries']:
        _url = ent['request']['url']
        _response = ent['response']
        _content = _response['content']['text']
    

    【讨论】:

    • 这似乎不起作用,条目是一个字典列表,其中包含“method”、“url”、“cookies”、“queryString”等键。但似乎有没有内容(即使'captureContent':True
    • 这对我有用。我能够在 proxy.har['log']['entries'][0]['response']['content']['text'] 中找到响应数据
    • 奇怪了,你用firefox驱动也搞定了吗?
    • @cglacet "method", "url", "cookies", "queryString"... 是请求对象的键,但这是关于响应体的话题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多