我在为网页中元素的 CSS 路径自动生成逻辑时遇到问题。
用例:当用户点击网页上的任何元素时,将使用 CSS 选择器概念(如 id-name、class-name、tag-name 和 nth-child)自动生成 CSS 选择器。
例如:假设我点击电子商务产品描述页面上的价格元素,我将得到类似于 body > ul:nth-child(27) > li:nth-child( 1)
。这里最大的 BANE 是 nth-child(1)
,因为对于这个页面,价格是第一个 child ,但对于其他页面,它可能是第 4 个或第 5 个或第 23 个 child 。而且,更大的问题是 price 元素的 HTML 是
<html>
....
<body>
<div>ABC</div>
<div>DEF
<span>GHI</span>
<ul>
<li> PRICE: $32.23 </div>
<li> WEIGHT: 100 lbs </div>
</ul>
</div>
</body>
</html>
没有任何类名或 ID 名。我当前的选择器生成逻辑会生成很多选择器组合,但会选择最独特的选择器。
请帮帮我!
最佳答案
<span class='product'>Cheese</span>
<ul class='product-details' >
<li class='price' id='Cheese-price'> PRICE: $32.23 </li>
<li class='weight' id='Cheese-weight'> WEIGHT: 100 lbs </li>
</ul>
<span class='product'>Apple</span>
<ul class='product-details' >
<li class='price' id='Apple-price'> PRICE: $2.23 </li>
<li class='weight' id='Apple-weight'> WEIGHT: 1 lbs </li>
</ul>
我的概念是你添加类来分类并根据产品名称和 -price
或 -weight
后缀制作唯一的 id,例如:Cheese-价格
。然后,您可能会使用一些 jquery 函数,这些函数通过类或属性名称的末尾来标识元素:-price
because for this page the price is the 1st child, but for other pages it could be 4th or 5th or 23rd child.
If I click on this PRICE: $23.32, then a JS function will read the textContent inside
li
elementI click on a price element on an e-commerce product description page
...but no database in involved here. Just the web page and its DOM
您是在服务器端生成 css 选择器,还是仅在用户点击时通过 js 函数
生成?如果是后者,那么你就进错了圈子。
更新
由于您尝试在客户端添加 css 选择器(在收到 HTML 页面后),我对您的建议是抓取漏洞页面,将其保存在本地并使用 regex 进行处理。基于单词 PRICE
和 WEIGHT
。例如:/PRICE:\s+\$([\.\d]+)/g
参见 working demo .
关于javascript - 自动生成 css 选择器的第 n 个子方法的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32099741/