首页 > 解决方案 > 如何通过 Selenium 快速获取网页上所有元素的大小和位置

问题描述

我需要获取网页上每个元素的大小和位置。如果我尝试幼稚的方法,那么它会非常慢(通常,处理一些常见页面(如 www.amazon.com 等)大约需要 2 分钟)。

是否有一些更快的方法来获取这些信息?

我天真的方法:

from selenium import webdriver

driver = webdriver.Chrome(..."\chromedriver.exe")
driver.get("https://www.amazon.com")

html = driver.find_element_by_tag_name('html')
for e in html.find_elements_by_css_selector("*"):
    size = e.size
    location = e.location

标签: pythonselenium

解决方案


我不确定您希望如何处理这些信息,但请使用 javascript 执行程序来运行以下 Javascript。如果您需要不同格式的数据,请随意编辑它,但您希望脚本使用它。获取所有这些信息大约需要 1 秒钟。

var returnValues = "";
var els = $("*:visible");
for(var x = 0; x < els.length; x++) {
  
  returnValues += `${$(els[x]).height()},${$(els[x]).width()},${$(els[x]).position().left},${$(els[x]).position().top}|`;
  console.log(`${$(els[x]).height()} x ${$(els[x]).width()}`);
  console.log(`pos: x:${$(els[x]).position().left} y:${$(els[x]).position().top}`);

}
return returnValues;

这可以通过启动var results = driver.execute_script("Above javascript").split("|");


推荐阅读