首页 > 解决方案 > 如何使用 selenium 和 Python 在此 URL 上单击此按钮?

问题描述

from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.keys import Keys
import configparser
from selenium.webdriver import ActionChains
import time
import os


class SeleniumConfig():

    def __init__(self):
        config = configparser.ConfigParser()
        self.absolute = "C:\\Program Files (x86)\\chromedriver.exe"
        options = webdriver.ChromeOptions()
        options.add_argument("--start-maximized")
        self.driver = webdriver.Chrome(self.absolute, options=options)

    def jupiter_1(self):
        self.driver.get('http://jupiter.cloud.planittesting.com')
        self.driver.find_element_by_id("nav-contact").click()
        time.sleep(5)
        form = self.driver.find_element_by_class_name(
            "btn-contact btn btn-primary") # my issue seems to start at the submit button
        time.sleep(5)
        self.driver.quit()

在此处输入图像描述

我不确定为什么我不能使用类名,因为检查表明它是

我的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".btn-contact btn btn-primary"}
  (Session info: chrome=87.0.4280.141)

标签: pythonseleniumselenium-webdriver

解决方案


self.driver.find_element_by_css_selector(".btn-contact.btn.btn-primary")

类名中的空格需要替换为 . 为了正确的xpathing。

也尽量不要使用 time.sleep() 并使用以下内容来允许页面加载和元素可点击。

wait = WebDriverWait(self.driver,10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,".btn-contact.btn.btn-primary"))).click()

进口

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

推荐阅读