【问题标题】:Can't locate any element in selenium在硒中找不到任何元素
【发布时间】:2020-12-03 16:01:04
【问题描述】:

请耐心等待,这是我的第一个真正的项目,我正在尝试借助 Python 和 Selenium 编写一个自动化的 Amazon.com 结帐代码。

目前最大的问题是 webdriver 似乎无法在定义的产品页面上找到“立即购买”和“确认结帐”按钮。我尝试了不同的方法(使用 XPATH、CSSSELECTOR 和 NAME),但都没有奏效。

有人给我小费吗?请在上面找到我的代码:

# This count variable is used to check if the product has been bought, if yes it will be 1.
count = 0
page_refreshed = 1
# This while loop is used to check for the "Buy Now" button until it is enabled by Amazon.
while count<= 1:

    # This try statement used to click on the "Buy now" Button and click the "Submit Order" Button on the following page
    try:
        buy_now = driver.find_element_by_css_selector('#buy-now-button')
        buy_now.click()
        driver.implicitly_wait(8)
        buy = driver.find_element_by_css_selector('#bottomSubmitOrderButtonId > span > input')
        buy.click()
        count += 2
        print("Buttons clicked! The item has been bought!");print()
    # This except statement used to reload the page every second until the add to cart option is enabled
    except:
        if count <= 1:
            print("Button not appeared, reloading...page reloaded "+str(page_refreshed)+" times!")
            driver.refresh()
            page_refreshed += 1
        pass

【问题讨论】:

标签: python selenium xpath automation selector


【解决方案1】:

由于页面刷新,第一个元素可能不会出现尝试使用 Webdriver 等待以允许页面加载。

buy_now = driver.find_element_by_css_selector('#buy-now-button')

替换为

buy_now=WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#buy-now-button")))

导入

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

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多