簡體   English   中英

如何使用Selenium-Python從網站上項目的另一個目錄上載圖像?

[英]How do I upload an image from another directory of my project on web site with Selenium - Python?

我需要在網站上上傳圖像,並且要將圖像存儲在項目中的單獨目錄“ image”中,以便每個人都可以運行我的測試並上傳圖像而沒有路徑問題。

這是上傳表單的html代碼:

<form id="imageUploadForm" class="ant-form ant-form-horizontal image-upload-form">
<div class="ant-row ant-form-item">
<div class="ant-col ant-form-item-label ant-col-xs-24 ant-col-sm-4">
<label class="" title="Image list">Image list</label>
</div>
<div class="ant-col ant-form-item-control-wrapper ant-col-xs-24 ant-col-sm-16">
<div class="ant-form-item-control">
<span class="ant-form-item-children">
<div class="images-list">
<div class="images-list__upload-btn">
<span class="">
<div class="ant-upload ant-upload-select ant-upload-select-text">
<span tabindex="0" class="ant-upload" role="button">
<input id="image" type="file" accept="" style="display: none;">
<button type="button" class="ant-btn image-upload__btn">
<i aria-label="icon: plus" class="anticon anticon-plus">
<svg viewBox="64 64 896 896" class="" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false">

至於上載表格:網站上沒有輸入字段,您只能通過系統窗口選擇文件。

這是我的代碼:

import os

image_upload = wd.find_element_by_xpath("//*[@id='imageUploadForm']/div[1]/div[2]/div/span/div/div[1]/span/div")

// tap on a button which opens a system window
 image_upload.click()

//trying to send path to a file which stored in my project
image_upload.send_keys(os.getcwd().replace("fixture", "") + "images/variant_1.png")

顯然,不起作用。 還閱讀了有關與“輸入文件”交互的信息,但未了解如何應用。

有任何想法嗎? 提前致謝!

您好,快照中有一個id為“ image”的輸入標簽。 請嘗試使用sendtext發送您願意上傳的圖像的路徑,然后單擊“提交”將起作用。

代碼應如下所示:

xpath ="//*[@id=\\"image\\"]; driver.FindElement(By.XPath(xpath)).SendKeys("Your image path");

然后在上傳按鈕上執行點擊事件,它將起作用

首先,有一個輸入元素,您將鍵發送給該輸入元素,而不是表單元素。 然后嘗試不要單擊輸入元素,因為它將觸發單擊事件並打開硒無法處理的os文件檢測器。

image_upload_input = wd.find_element_by_xpath("//*[@id='image']")
image_upload.send_keys(os.getcwd().replace("fixture", "") + "images/variant_1.png")

如果以某種方式發送密鑰仍觸發打開os文件檢測器,則需要使用file_detector中的file_detector覆蓋它:

from selenium.webdriver.remote.file_detector import UselessFileDetector
wd.file_detector = UselessFileDetector()

簡而言之,整個代碼將是:

from selenium.webdriver.remote.file_detector import UselessFileDetector
wd.file_detector = UselessFileDetector()
image_upload_input = wd.find_element_by_xpath("//*[@id='image']")
image_upload.send_keys(os.getcwd().replace("fixture", "") + "images/variant_1.png")

暫無
暫無

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

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