在 AJAX 驱动的网站上选择正确的控件
导航 AJAX 驱动的网站并与之交互对于自动化脚本来说可能具有挑战性。以下是有效自动化此类网站的分步指南:
具体示例:Nike 自动购买脚本
目标: 选择特定的鞋子尺码,将其添加到购物车,然后继续结帐每双耐克运动鞋
步骤:
关键元素识别:
事件序列:
完整脚本:
// ==UserScript== // @name Nike Auto-Buy Shoes // @include http*://store.nike.com/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== var targetShoeSize = "10"; //-- Step 1: Activate Size Dropdown waitForKeyElements( "div.footwear form.add-to-cart-form span.sizeDropdown a.size-dropdown", activateSizeDropdown ); function activateSizeDropdown(jNode) { triggerMouseEvent(jNode[0], "mousedown"); //-- Setup Step 2 waitForKeyElements( "ul.selectBox-dropdown-menu li a:contains('" + targetShoeSize + "'):visible", selectDesiredShoeSize ); } //-- Step 2: Select Target Shoe Size function selectDesiredShoeSize(jNode) { if ($.trim(jNode.text()) === targetShoeSize) { //-- Trigger triplex event triggerMouseEvent(jNode[0], "mouseover"); triggerMouseEvent(jNode[0], "mousedown"); triggerMouseEvent(jNode[0], "mouseup"); //-- Setup Steps 3 and 4 waitForKeyElements( "div.footwear form.add-to-cart-form span.sizeDropdown a.selectBox span.selectBox-label:contains('(" + targetShoeSize + ")')", waitForShoeSizeDisplayAndAddToCart ); } } //-- Steps 3 and 4: Wait for Shoe Size Display and Add to Cart function waitForShoeSizeDisplayAndAddToCart(jNode) { var addToCartButton = $( "div.footwear form.add-to-cart-form div.product-selections div.add-to-cart" ); triggerMouseEvent(addToCartButton[0], "click"); //-- Setup Step 5 waitForKeyElements( "div.mini-cart div.cart-item-data a.checkout-button:visible", clickTheCheckoutButton ); } //-- Step 5: Click the Checkout Button function clickTheCheckoutButton(jNode) { triggerMouseEvent(jNode[0], "click"); } function triggerMouseEvent(node, eventType) { var clickEvent = document.createEvent("MouseEvents"); clickEvent.initEvent(eventType, true, true); node.dispatchEvent(clickEvent); }
以上是如何有效地自动化 AJAX 驱动的网站交互?的详细内容。更多信息请关注PHP中文网其他相关文章!