努力让 Selenium 完成自动结账

问题描述

我一直在尝试使用 Selenium,并一直试图让我的自动结账工作正常进行。到目前为止,它非常成功,但我遇到了一个障碍,我的代码的最后部分似乎无法正常工作。我试过以我能想到的各种方式安排我的“睡眠”和“隐式等待”,但没有成功。我一直被抛出“selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[@id="creditCardNumber"]” 如果有人能帮我解决这个问题,我将不胜感激!


from selenium.webdriver import Firefox
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time

driver = Firefox()
action = webdriver.ActionChains(driver)


def get_nike():

    driver.maximize_window()
    driver.get('https://www.nike.com/')

    men_shoes = driver.find_element_by_xpath('/html/body/div[1]/div[3]/header/div/div[1]/div[2]/nav/div[2]/ul/li[2]/a')
    action.move_to_element(men_shoes)
    action.perform()

    new_releases = driver.find_element_by_xpath('/html/body/div[1]/div[3]/header/div/div[1]/div[2]/nav/div[2]/ul/li[2]/div/div/div[1]/a[1]')
    avoid_wrong_selection = driver.find_element_by_xpath('/html/body/div[1]/div[3]/header/div/div[1]/div[2]/nav/div[2]/ul/li[2]/div/div/div[2]/a[2]')
    action.move_to_element(avoid_wrong_selection)
    action.move_to_element(new_releases)
    action.perform()
    new_releases.click()  # you have to click the element itself

    driver.implicitly_wait(2)

    selected_shoes = driver.find_element_by_xpath('//*[@id="Wall"]/div/div[5]/div[2]/main/section/div/div[12]/div/figure/a[2]/div/div/img') #can also use linked text
    driver.execute_script("arguments[0].scrollIntoView();",selected_shoes) # scrolls to shoes
    selected_shoes.click()

    get_size = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[3]/div[3]/div[2]/div/div/div[4]/form/div[1]/fieldset/div/div[10]/label')
    action.move_to_element(get_size)  # selects size
    get_size.click()

    time.sleep(1)

    add_bag = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[3]/div[3]/div[2]/div/div/div[4]/form/div[2]/div/div') #requires web element
    action.move_to_element(add_bag) # adds item to bag
    add_bag.click() 

    to_checkout = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[4]/div/div/div/div/div/div/div/div/div/div[3]/div/button[2]')
    action.move_to_element(to_checkout) # brings you to cart
    to_checkout.click()

    first_name = driver.find_element_by_xpath('//*[@id="firstName"]')
    first_name.send_keys("Bingo")

    last_name = driver.find_element_by_xpath('//*[@id="lastName"]')
    last_name.send_keys("Bongo")

    transition_address = driver.find_element_by_xpath('//*[@id="search-address-input"]')
    transition_address.send_keys('1453 E curfluffle street')

    manual_address = driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div/div[2]/div/div/main/section[2]/div/div[2]/form/div/div/div/div[1]/div[4]/div/div[2]/div/div/ul/li[3]/a')
    manual_address.click()

    real_address = driver.find_element_by_xpath('//*[@id="address1"]') # types address
    real_address.send_keys('53 sterling street')

    city = driver.find_element_by_xpath('//*[@id="city"]') # types city
    city.send_keys('pittsburgh')

    state_dropdown = driver.find_element_by_xpath('//*[@id="state"]')
    selections = Select(state_dropdown) # selects state from the dropdown
    
    selections.select_by_value("PA")

    zip_code = driver.find_element_by_xpath('//*[@id="postalCode"]')
    zip_code.send_keys('15203') #sends zip code

    email = driver.find_element_by_xpath('//*[@id="email"]')
    email.send_keys('gythfnjgfvn@gmail.com')

    phone_number = driver.find_element_by_xpath('//*[@id="phoneNumber"]')
    phone_number.send_keys('456-906-2354')

    save_and_continue = driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div/div[2]/div/div/main/section[2]/div/div[2]/form/div/div/div/div[2]/button')
    action.move_to_element(save_and_continue)
    save_and_continue.click()

    time.sleep(1)

    continue_to_payment = driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div/div[2]/div/div/main/section[2]/div/div[3]/div/button')
    action.move_to_element(continue_to_payment)
    continue_to_payment.click()

    
    cc_number = driver.find_element_by_xpath('//*[@id="creditCardNumber"]')
    driver.implicitly_wait(5)
    #scroll down to card info and enter card info
    driver.execute_script("arguments[0].scrollIntoView();",cc_number)
    time.sleep(2)
    cc_number.send_keys('123456789101112')

get_nike()

问题特别结束。

    continue_to_payment = driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div/div[2]/div/div/main/section[2]/div/div[3]/div/button')
    action.move_to_element(continue_to_payment)
    continue_to_payment.click()

    
    cc_number = driver.find_element_by_xpath('//*[@id="creditCardNumber"]')
    driver.implicitly_wait(5)
    #scroll down to card info and enter card info
    driver.execute_script("arguments[0].scrollIntoView();",cc_number)
    time.sleep(2)
    cc_number.send_keys('123456789101112')

解决方法

只需使用 webdriver wait 等待元素弹出并发送密钥即可。

wait.until(EC.element_to_be_clickable((By.ID,"creditCardNumber"))).send_keys("123456789101112")

修复其他代码以使其更稳定。

wait = WebDriverWait(driver,10)
action = webdriver.ActionChains(driver)
def get_nike():

    driver.maximize_window()
    driver.get('https://www.nike.com/')

    men_shoes = wait.until(EC.element_to_be_clickable((By.XPATH,"//a[@aria-label='Men']")))
    action.move_to_element(men_shoes).perform()

    new_releases = driver.find_element_by_xpath("//a[@role='menuitem' and text()='New Releases']")
    action.move_to_element(new_releases).click().perform()

    selected_shoes = wait.until(EC.element_to_be_clickable((By.XPATH,"//a[@aria-label='Nike ZoomX Invincible Run Flyknit']//img")))
    selected_shoes.click()

    get_size = wait.until(EC.element_to_be_clickable((By.XPATH,"//label[text()='US 10.5']")))
    get_size.click()

导入

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

使用此代码段检查 WebElement 在视口中是否可见,不要使用 selenium 等待,它们有很多错误。

import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd

# function getting data for the last x years with x weeks space from checking data and specific 
observation.
def stock_data(ticker,period,interval,observation):
    ticker = yf.Ticker(ticker)
    ticker_history = ticker.history(period,interval)
    print(ticker_history[observation]) #is here to show you the data that we get
    date = pd.date_range(ticker_history[period])
    x = date 
    y = np.array(ticker_history[observation])
    plt.style.use('dark_background')
    plt.plot(x,y)
    plt.ylabel('Price($)')
    plt.xlabel('Date',rotation=0)
    plt.show()

stock_data('GOOGL','6mo','1wk','Open')

只需将 Java 方法转换为 Python 函数并将您要查找的 WebElement 传递给它即可。