簡體   English   中英

如何使用 selenium 和 Python 在此 URL 上單擊此按鈕?

[英]How to click this button on this URL using selenium and Python?

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()

在此處輸入圖像描述

我不確定為什么我不能使用 class 名稱,因為檢查表明它是

我的錯誤:

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)
self.driver.find_element_by_css_selector(".btn-contact.btn.btn-primary")

class 名稱中的空格需要替換為。 為了正確的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

根據我對 selenium 的經驗, find_element_by_可能有點不穩定,有時您必須嘗試幾種參考技術才能最終起作用。 我建議使用完整的 Xpath,因為它似乎可靠地工作(它的缺點是在代碼本身中讀取並不那么明顯)。 您可以通過檢查 html 開發工具中的元素來獲得 xpath,然后右鍵單擊以復制它。 “復制完整 xpath”的選項應該出現在某處。

考慮到這一點,您可以嘗試以下代碼行,看看它是否有幫助:

form = driver.find_element_by_xpath("/html/body/div[2]/div/form/div/a")

希望這至少可以為您指明正確的方向!

沒關系,我找到了答案或解決方法=>

form = self.driver.find_element_by_link_text("提交")

我使用 find_element_by_link_text 提交並且它有效。

請使用以下相關 xpath 點擊提交按鈕

//a[@class='btn-contact btn btn-primary']

暫無
暫無

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

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