【问题标题】:Selenium get .har fileSelenium 获取 .har 文件
【发布时间】:2015-05-18 19:56:27
【问题描述】:

我有一个两页的应用程序:
/登录
/个人资料
我想获取 .har 文件页面 /profile
当我进入 /login 页面时,cookie 是使用 key=connect.sid 和 value = "example value" 创建的。此 cookie 尚未激活。 我添加了带有活动 connect.sid 的 cookie。

WebDriver webDriver = getDriver();
webDriver.get(LOGIN_PAGE);
webDriver.manage().addCookie(connectsSId);

它不起作用,因为在加载页面后,/login 创建了一个新的 cookie。 我也试过这段代码:

WebDriver webDriver = getDriver();
webDriver.get(PROFILE_PAGE);
webDriver.manage().deleteAllCookies();
webDriver.manage().addCookie(connectsSId);

这不起作用。 cookie 已添加,但似乎为时已晚。

 WebDriver webDriver = getDriver();
 LoginPage loginPage = new LoginPage(getDriver());
 LandingPage landingPage = loginPage.login();
 landingPage.openProfilePage();

此代码为 /login 页面创建了一个 .har 文件。
由于某种原因,文件仅在第一次调用页面后创建。我无法解决这个问题。

【问题讨论】:

    标签: java selenium browsermob


    【解决方案1】:

    您可以使用 browsermob 代理来捕获所有请求和响应数据 See here

    【讨论】:

      【解决方案2】:

      将 PhantomJS 与 BrowserMobProxy 一起使用。 PhantomJS 帮助我们为 JavaScript 启用页面。以下代码也适用于 HTTPS 网址。

      'phantomjs.exe' 放在 C 盘中,您会在 C 盘中获得 'HAR-Information.har' 文件。

      确保您不要在网址末尾添加 ' / ',例如

      driver.get("https://www.google.co.in/")
      

      应该是

      driver.get("https://www.google.co.in");
      

      否则将无法正常工作。

      package makemyhar;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.util.ArrayList;
      import net.lightbody.bmp.BrowserMobProxy;
      import net.lightbody.bmp.BrowserMobProxyServer;
      import net.lightbody.bmp.core.har.Har;
      import net.lightbody.bmp.proxy.CaptureType;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.phantomjs.PhantomJSDriver;
      import org.openqa.selenium.phantomjs.PhantomJSDriverService;
      import org.openqa.selenium.remote.CapabilityType;
      import org.openqa.selenium.remote.DesiredCapabilities;
      
      public class MakeMyHAR {
          public static void main(String[] args) throws IOException, InterruptedException {
      
              //BrowserMobProxy
              BrowserMobProxy server = new BrowserMobProxyServer();
              server.start(0);
              server.setHarCaptureTypes(CaptureType.getAllContentCaptureTypes());
              server.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
              server.newHar("Google");
      
              //PHANTOMJS_CLI_ARGS
              ArrayList<String> cliArgsCap = new ArrayList<>();
              cliArgsCap.add("--proxy=localhost:"+server.getPort());
              cliArgsCap.add("--ignore-ssl-errors=yes");
      
              //DesiredCapabilities
              DesiredCapabilities capabilities = new DesiredCapabilities();
              capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
              capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true);
              capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
              capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"C:\\phantomjs.exe");
      
              //WebDriver
              WebDriver driver = new PhantomJSDriver(capabilities);
              driver.get("https://www.google.co.in");
      
              //HAR
              Har har = server.getHar();
              FileOutputStream fos = new FileOutputStream("C:\\HAR-Information.har");
              har.writeTo(fos);
              server.stop();
              driver.close();
          }
      }
      

      【讨论】:

        【解决方案3】:

        在您的 Selenium 代码中设置首选项:

            profile.setPreference("devtools.netmonitor.har.enableAutoExportToFile", true);
        profile.setPreference("devtools.netmonitor.har.defaultLogDir", String.valueOf(dir));
        profile.setPreference("devtools.netmonitor.har.defaultFileName", "network-log-file-%Y-%m-%d-%H-%M-%S");
        

        然后打开控制台:

        Actions keyAction = new Actions(driver);
        keyAction.keyDown(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).sendKeys("q").keyUp(Keys.LEFT_CONTROL).keyUp(Keys.LEFT_SHIFT).perform();
        

        【讨论】:

        • 这看起来是一个非常有吸引力的解决方案。但是我如何从司机那里获得个人资料?例如:driver = new ChromeDriver(chromeOptions);
        • @creathor :根据这个问题:stackoverflow.com/questions/58611579/… 似乎偏好是 Firefox 功能和 chrome 使用选项。这个答案似乎是特定于 Firefox 的。
        【解决方案4】:

        我也尝试过使用像 browsermob 代理这样的代理来获取 har 文件

        我做了很多研究,因为我收到的文件总是空的。

        我所做的是启用浏览器性能日志。

        请注意,这仅适用于 chrome 驱动程序。

        这是我的驱动程序类(在 python 中)

        from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
        from selenium import webdriver
        from lib.config import config
        
        
        class Driver:
        
            global performance_log
            capabilities = DesiredCapabilities.CHROME
            capabilities['loggingPrefs'] = {'performance': 'ALL'}
        
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--disable-dev-shm-usage')
            chrome_options.add_argument("--headless")
            mobile_emulation = {"deviceName": "Nexus 5"}
        
            if config.Env().is_mobile():
                chrome_options.add_experimental_option(
                    "mobileEmulation", mobile_emulation)
            else:
                pass
        
            chrome_options.add_experimental_option(
                'perfLoggingPrefs', {"enablePage": True})
        
            def __init__(self):
                self.instance = webdriver.Chrome(
                    executable_path='/usr/local/bin/chromedriver', options=self.chrome_options)
        
            def navigate(self, url):
                if isinstance(url, str):
                    self.instance.get(url)
                    self.performance_log = self.instance.get_log('performance')
                else:
                    raise TypeError("URL must be a string.")
        

        在输出中发现的信息量很大,因此您必须过滤原始数据并仅让网络接收和发送对象。

        import json
        import secrets
        
        
        def digest_log_data(performance_log):
            # write all raw data in a file
            with open('data.json', 'w', encoding='utf-8') as outfile:
                json.dump(performance_log, outfile)
            # open the file and real it with encoding='utf-8'
            with open('data.json', encoding='utf-8') as data_file:
                data = json.loads(data_file.read())
                return data
        
        
        def digest_raw_data(data, mongo_object={}):
            for idx, val in enumerate(data):
                data_object = json.loads(data[idx]['message'])
                if (data_object['message']['method'] == 'Network.responseReceived') or (data_object['message']['method'] == 'Network.requestWillBeSent'):
                    mongo_object[secrets.token_hex(30)] = data_object
                else:
                    pass
        

        我们选择将这些数据推送到 mongo db 中,稍后将由 etl 进行分析并推送到 redshift 数据库中以创建统计信息。

        我希望是你正在寻找的。​​p>

        我运行脚本的方式是:

        import codecs
        from pprint import pprint
        import urllib
        from lib import mongo_client
        from lib.test_data import test_data as data
        from jsonpath_ng.ext import parse
        from IPython import embed
        from lib.output_data import process_output_data as output_data
        from lib.config import config
        from lib import driver
        
        browser = driver.Driver()
        
        # get the list of urls which we need to navigate
        urls = data.url_list()
        
        for url in urls:
            browser.navigate(config.Env().base_url() + url)
            print('Visiting ' + url)
            # get performance log
            performance_log = browser.performance_log
            # digest the performace log
            data = output_data.digest_log_data(performance_log)
            # initiate an empty dict
            mongo_object = {}
            # prepare the data for the mongo document
            output_data.digest_raw_data(data, mongo_object)
            # load data into the mongo db
            mongo_client.populate_mongo(mongo_object)
        
        
        browser.instance.quit()
        

        我的主要来源是这个,我已经根据自己的需要对其进行了调整。 https://www.reddit.com/r/Python/comments/97m9iq/headless_browsers_export_to_har/ 谢谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-28
          • 1970-01-01
          • 1970-01-01
          • 2016-04-12
          • 1970-01-01
          • 1970-01-01
          • 2018-07-19
          相关资源
          最近更新 更多