我正在嘗試單擊網頁上的輸入按鈕
<input type="button" id="add-to-wishlist-button-5" class="button-2 add-to-wishlist-button" value="Add to wishlist" data-productid="5" onclick="AjaxCart.addproducttocart_details('/addproducttocart/details/5/2', '#product-details-form');return false;">
使用這樣的代碼:
driver = webdriver.Edge(executable_path='C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedgedriver.exe')
driver.get('https://demowebshop.tricentis.com/')
driver.maximize_window()
category = driver.find_element(By.LINK_TEXT,"Apparel & Shoes")
category.click()
links = driver.find_elements(By.CSS_SELECTOR,"div.product-grid a")
random.choice(links).click()
wish_list = browser.find_element(By.XPATH,"//input[@value='Add to wishlist']")
wish_list.click()
但在線
wish_list = browser.find_element(By.XPATH,"//input[@value='Add to wishlist']")
得到錯誤作為這個問題的標題
uj5u.com熱心網友回復:
對于產品串列中的少數產品,一些產品沒有“添加到愿望”按鈕。所以你必須對沒有元素進行適當的錯誤處理。
from selenium.common.exceptions import NoSuchElementException
try:
wish_list = browser.find_element(By.XPATH,"//input[@value='Add to wishlist']")
wish_list.click()
except NoSuchElementException: # Error catch here
print('No Add to wish button available.')
uj5u.com熱心網友回復:
我在這里看到了以前的答案未涵蓋的 2 個問題:
- 您使用的所有代碼
driverwhile 用于您正在使用的最后一個元素browser。這可能是一個錯字,但你的代碼將永遠無法作業。 - 您需要添加延遲以等待元素可點擊性。
我沒用random.choice,只是看看代碼基本能用。
因此,以下代碼運行穩定:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
url = 'https://demowebshop.tricentis.com/'
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Apparel & Shoes"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.product-grid a"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@value='Add to wishlist']"))).click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517188.html
上一篇:從自定義屬性中獲取屬性文本
