如何使用Python/Java中的Selenium访问Chrome Dev工具网络选项卡的请求或概要值?

4
我正在使用Chrome选项通过Selenium访问性能日志,我正在尝试编写一段代码来帮助我确定加载完成后的HTTP请求总数和页面大小。手动可以通过使用Dev工具的网络选项卡来检查这一点。只需要知道如何访问网络表的值或摘要值。因为性能日志没有给我所需的摘要值,我想编写一段代码来获取:

请求数的总数=

页面的总大小是多少=

如果可能的话。 网络选项卡截图突出显示我需要访问的摘要和请求表格值
capabilities = DesiredCapabilities.CHROME
capabilities['loggingPrefs'] = {'browser': 'DEBUG'}
capabilities['loggingPrefs'] = {'performance': 'ALL'}
capabilities['perfLoggingPrefs'] = {'enableTimeline': 'true'}


driverLocation = "/Users/harisrizwan/Selenium/chrome/chromedriver"
os.environ["chrome.driver"] = driverLocation
chrome_options = Options()
chrome_options.add_argument("headless")

driver= 
webdriver.Chrome(driverLocation,desired_capabilities=capabilities)
driver.implicitly_wait(10)
driver.maximize_window()
baseUrl="www.google.com"
driver.get(baseUrl)

使用pandas创建日志数据框。
df = pd.DataFrame(driver.get_log('performance'))
df.to_clipboard(index=False)

谢谢。

3个回答

3
我不确定如何计算页面的总重量,但是获取发送到服务器的请求总数是可能的。
使用 https://github.com/lightbody/browsermob-proxy 并将代理添加到所需的能力中,一旦脚本完成,将har文件转储为json并获取所有请求。
在Python中:
from browsermobproxy import Server
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json

server = Server('path to the proxy server file')
server.start()
proxy = server.create_proxy()

options = Options()
options.add_argument(f'--proxy-server={proxy.proxy}')
driver = webdriver.Chrome('path to chromedriver', desired_capabilities=options.to_capabilities())

proxy.new_har()
driver.get('https://www.google.com')

result = json.dumps(proxy.har)
json_data = json.loads(result)

request= [x for x in json_data['log']['entries']]
server.stop()
driver.close()

2
你可以使用性能 API来获取传输大小。
主页面和每个资源的传输大小:
sizes = driver.execute_script("""
  return performance.getEntries()
    .filter(e => e.entryType==='navigation' || e.entryType==='resource')
    .map(e=> ([e.name, e.transferSize]));
  """)

主页面的传输大小仅为:
size = driver.execute_script("""
  return performance.getEntriesByType('navigation')[0].transferSize;
  """)

主页面和资源的总传输大小:
size = driver.execute_script("""
  return performance.getEntries()
    .filter(e => e.entryType==='navigation' || e.entryType==='resource')
    .reduce((acc, e) => acc + e.transferSize, 0)
  """)

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接