在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中文網其他相關文章!