簡體   English   中英

動態網站按類名查找元素,並在 Python 中使用 Selenium 和 Chrome 執行與該類關聯的 onclick 方法

[英]Dynamic website find element by class name and execute onclick method associated with the class in Python with Selenium and Chrome

我正在研究 Python、Selenium 和 Chrome 驅動程序。 我有一個動態網站,每次網站加載時 ID 都會更改,因此我無法使用 Xpath。 但是我可以使用類名。 我可以按如下方式上課; 以下是網站的代碼。

<a class="appButton registerItemSearch-tabs-criteriaAndButtons-buttonPad-search appSearchButton appPrimaryButton appButtonPrimary appSubmitButton appNotReadOnly appIndex2" id="nodeW830" href="#" onclick="return function(me){var retVal = false; if (catHtmlFragmentCallback('W830','buttonPush',null,{asyncUpdate:true,containerSelector:'#AsyncWrapperW814',containerNodeId:'W814',success:function(html){jQuery('#AsyncWrapperW814').empty().append(html);webuiAsyncOk('#AsyncWrapperW814');}}, me) == 'skip') retVal = true;return retVal;}(this)" tabindex="118"><span class="left"></span><span class="appReceiveFocus" tabindex="-1">Search</span><span class="right"></span></a>

但是我可以執行以下操作; 到達元素。

xxx = driver.find_elements_by_class_name("appButton.registerItemSearch-tabs-criteriaAndButtons-buttonPad-search.appSearchButton.appButtonPrimary.appPrimaryButton.appSubmitButton.appNotReadOnly.appIndex2")

現在我想執行與類關聯的 onclick 方法。 我也可以像下面那樣這樣做;

driver.execute_script("return function(me){var retVal = false; if (catHtmlFragmentCallback('W830','buttonPush',null,{asyncUpdate:true,containerSelector:'#AsyncWrapperW814',containerNodeId:'W814',success:function(html){jQuery('#AsyncWrapperW814').empty().append(html);webuiAsyncOk('#AsyncWrapperW814');}}, me) == 'skip') retVal = true;return retVal;}(this)")

但正如我所提到的,我無法對 driver.execute_script 值進行硬編碼。 我應該動態獲取值。 請你幫助我好嗎? 如果你能提出一種方法,我可以通過類名找到元素並執行 onclick 方法。 或者正如我所提到的; 我可以通過類名找到元素,如果我可以獲得與元素關聯的代碼 (HTML),那么我可以執行 driver.execute_script。 你能提出一個前進的方向嗎? 謝謝

誘導WebDriverWaitelement_to_be_clickable () 和以下定位器。

路徑

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//a[.//span[text()='Search']]"))).click()

CSS 選擇器

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"a.appButton.registerItemSearch-tabs-criteriaAndButtons-buttonPad-search.appSearchButton.appPrimaryButton.appButtonPrimary.appSubmitButton.appNotReadOnly.appIndex2"))).click()

您需要導入以下庫。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM