我正在为wrapper使用python browsermob proxy,我需要修改服务器响应。但我无法弄清楚我是如何做到的。任何人都可以给我一个有效的代码示例吗?
文档说我可以为它发送一个javascript代码,但它对我不起作用:
server = Server(path=SCRIPT_DIR+"/browsermob-proxy/bin/browsermob-proxy", options={"port": 8888})
server.start()
proxy = server.create_proxy()
proxy.response_interceptor('contents.setTextContents("<html><body>Response successfully intercepted</body></html>")')
fp = webdriver.FirefoxProfile()
browser = webdriver.Firefox(firefox_profile=fp, proxy=proxy)
browser.get("http://example.com")
谢谢!
答案 0 :(得分:0)
在browsermobproxy版本0.7.1中,响应了response_interceptor。您可以转到github并获取最新代码,或者您可以使用此解决方法而不是response_interceptor:
import requests
url = proxy.host + '/proxy/' + str(proxy.port) + '/filter/response'
headers={'Content-Type':'text/plain'}
filter = "contents.setTextContents('<html><body>Response successfully intercepted</body></html>');"
r = requests.post(url=url, data=filter, headers=headers)
答案 1 :(得分:0)
像魅力一样工作 - 只是不要忘记在Firefox配置文件上设置代理;)fp.set_proxy(proxy.selenium_proxy())
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
from browsermobproxy import Server
from pprint import pprint
from time import sleep
import requests
server = Server($PATH_GOES_HERE$)
server.start()
proxy = server.create_proxy()
proxy.new_har('test111')
url = proxy.host + '/proxy/' + str(proxy.port) + '/filter/response'
headers={'Content-Type':'text/plain'}
filter = "response.setTextContents('<html><body>Response successfully intercepted</body></html>');"
r = requests.post(url=url, data=filter, headers=headers)
fp = webdriver.FirefoxProfile()
fp.set_proxy(proxy.selenium_proxy()) # <---- you forgot this one here ;)
browser = webdriver.Firefox(firefox_profile=fp, proxy=proxy)
sleep(3)
browser.get("example.com")