[英]How to make selenium(Chrome) webdriver wait until there is no pending request in the network? (Using JAVA)
[英]How to access the values of Chrome's Dev tools Network tab's Request or summary using Selenium in python/java?
我正在使用 chrome 选项使用 selenium 访问性能日志记录,我正在尝试编写一个代码来帮助我计算出 http 请求的总数以及加载完成后页面的大小。 我们可以使用 Dev 工具的 .network 选项卡手动检查这一点。 只需要知道如何访问网络表的值或汇总值。 因为性能日志没有给我我需要的汇总值,我想写一个代码来获取:
请求总数=
Page的总权重是多少=
如果可能。
.network 选项卡的屏幕截图突出显示了我需要访问的摘要和请求表值
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)
df = pd.DataFrame(driver.get_log('performance'))
df.to_clipboard(index=False)
谢谢。
我不确定计算页面的总重量,但可以获得发送到服务器的请求总数
使用https://github.com/lightbody/browsermob-proxy并将代理添加到desired_capabilities,一旦脚本完成,将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()
您可以使用性能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)
""")
2021 年更新:
从 2020/2021 开始,这现在可以作为 Selenium 4 Beta 的一部分。 整个 chrome 开发工具套件可通过原生 selenium API 使用。
请参阅: https://www.selenium.dev/documentation/support_packages/chrome_devtools/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.