python - 如何通过 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
解决方案
我不确定您希望如何处理这些信息,但请使用 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("|");
推荐阅读
- python - while循环,询问用户是否想重复程序问题
- reactjs - 为什么 NextJS 中的 ApolloGraphQL 示例使用 getStaticProps 而不是 getServerSideProps
- laravel - 如何在第三个关系中获得带有条件的查询?
- merge - Apache POI(Word)合并表格中的单元格
- javascript - 自动从 Input id="message2" 生成二维码,无需用户点击任何额外内容
- maven - 为什么我们要在 Maven 中定义一个依赖的范围?
- javascript - 如何在传单地图中添加搜索栏以及如何将搜索位置的纬度和经度分配给变量,以便我以后使用它们
- racket - 球拍骰子功能
- javascript - Chrome 扩展 - Chrome.storage - 为什么 chrome.storage.sync.get 返回未定义?
- javascript - 使用 useTracker meteor subscribe 和 findOne mongo 检查 !isLoading 和 state 是否存在