簡體   English   中英

有沒有辦法在無頭 chrome 中使用 selenium 上傳文件?

[英]Is there any way to upload file using selenium in headless chrome?

我正在創建一個需要我上傳文件的腳本,所以我寫了如下內容:

    @FindBy(css = "div[title='Add an attachment'] button")
    private WebElementFacade FILE_UPLOAD_BUTTON;

    Path path = Paths.get(System.getProperty("user.dir"));

    withTimeoutOf(20, TimeUnit.SECONDS).waitFor(ExpectedConditions.visibilityOf(FILE_UPLOAD_BUTTON));
    FILE_UPLOAD_BUTTON.click();

    filePath = Paths.get(path.toString(), "FolderName", "ActualFileName.pdf");

    StringSelection fullPath = new StringSelection(filePath.toString());
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(fullPath, fullPath);

    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    pause(2000);

它工作正常,但在 Headless chrome 中則不行。 關於如何在 Headless chrome 中上傳文件的任何想法? TIA。

編輯:添加了對 serenity 的查詢,wakaleo 懷疑 Robot 類是否可以在無頭 chrome 上運行,因為它與真實的 UI 交互。 我還嘗試了他的建議,使用標准 Selenium 操作,如chord org.openqa.selenium.Keys; actions org.openqa.selenium.interactions.Actions; 兩者都沒有工作

您可以使用AutoIt及其編輯器在硒中上傳文件

1.您需要安裝Autoit及其腳本編輯器

我已經分享了鏈接,您可以下載和使用它

https://www.autoitscript.com/site/autoit/downloads/

  1. 您需要創建autoit文件並需要傳遞文件位置和一些腳本,並根據需要命名文件,就像我給了File Upload.au3一樣,.au3擴展名自動出現

     ControlFocus("Open","","Edit1") ControlSetText("Open","","Edit1","E:\\AutoIT\\id.pdf") ControlClick("Open","","Button1") 
  2. 您需要右鍵單擊文件upload.au3文件並進行編譯,然后它將創建執行文件File Upload.exe

  3. 然后您需要在硒中指定需要執行和上傳文件的位置,就像在我的項目中一樣,在單擊“上傳”按鈕后,我正在使用Runtime.getRuntime().exec(Globals.PROG_FILEUPLOAD);執行此文件Runtime.getRuntime().exec(Globals.PROG_FILEUPLOAD);

其中Global.PROG_FILEUPLOAD是文件Upload.exe的路徑,例如

PROG_FILEUPLOAD= "E:/AutoIT/File Upload.exe"

如果您有任何疑問,我也分享了鏈接,供您參考。

https://www.guru99.com/use-autoit-selenium.html

它不起作用,因為您使用的是Robot類,這對於無頭執行來說並不理想,因為無論如何瀏覽器都不可見。

確保您的上傳元素可見。

之后,您使用以下內容上傳:

driver.findElement(By.id("uploadElement")).sendKeys("path/to/file");

使用以下代碼以無頭模式上傳文件:

    ChromeOptions options = new ChromeOptions();
            options.addArguments("--headless");
            WebDriver driver = new ChromeDriver(options);
            driver.get("http://nervgh.github.io/pages/angular-file-upload/examples/simple/");
            driver.findElement(By.xpath("(//input[@uploader='uploader'])[2]")).sendKeys("C:\\NotBackedUp\\Python\\selenium-2.7.0\\py\\selenium\\selenium.py");
// Then click on some upload button

在sendKeys()方法中給出要上傳的文件的確切完整路徑。

是的,您可以使用sendkeys通過無頭 chrome 上傳文件。

  • 關鍵點在這里找出合適的元素。
  • sendkeys 與輸入標簽完美配合(文件作為文件上傳的類型)。
  • 如果它被包裝在其他標簽中,找出輸入標簽引用
  • 看看下面的例子
<p-fileupload id="file_upload_id">
   <div >
      <span>
        <span>Choose file</span>
        <input type="file" accept=".csv">
      </span>
   </div>
</p-fileupload>
  • 使用 xpath 查找元素
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.WebElement;

@FindBy(xpath="//[@id=\"file_upload_id\"]//following::input[@type=\"file\"]")
@CacheLookup
private WebElement fileupload;
  • 設置無頭鍍鉻驅動程序
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public  static void initialization() {  
   String browsername=prop.getProperty("browser");
    if(browsername.equals("chrome")) 
    { 
     System.setProperty("webdriver.chrome.driver","...//path-to-chrome-driver//Drivers//chromedriver");
     ChromeOptions chromeOptions = new ChromeOptions();
     chromeOptions.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200","--ignore-certificate-errors","--disable-extensions","--no-sandbox","--disable-dev-shm-usage");
     driver=new ChromeDriver(chromeOptions);
   }

  • 使用 sendkey 發送文件
String userDir = System.getProperty("user.dir");
String sep = System.getProperty("file.separator");
String path=userDir + sep + "Files_dir_name" + sep + "sample.csv";
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); 
fileupload.sendKeys(value);

注意:userDir - 項目運行的根目錄,文件分隔符 - 解決跨操作系統的文件路徑問題

暫無
暫無

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

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