如何使用JS Executor使用Selenium WebDriver在Chrome中使用属性(HREF)下载文件



我想在C#中的Selenium Web驱动程序中下载文件。我在Web元素中将URL作为属性HREF。使用该URL,我必须通过JavaScript执行程序下载文件。我尝试使用JS executeCript以字节的形式获取文件,然后将其转换为PDF文件并存储在我所需的位置。但是没有运气

IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.win-rar.com/predownload.html?&L=0");
string linkVal = driver.FindElement(By.LinkText("Download WinRAR")).GetAttribute("href");
var href = "https://www.win-rar.com/fileadmin/winrar-versions/winrar/winrar-x64-571.exe";
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
///  Object reposne = js.ExecuteScript("arguments[0].setAttribute(arguments[1],arguments[2])", linkVal, "href", "https://www.win-rar.com/postdownload.html?&L=0");
String script = "document.querySelector('a[href*="/print/"]').setAttribute('download','name-of-the-download-file-recommend-guid-or-timestamp.pdf');";
///Object reposne = js.ExecuteAsyncScript(script , href);
var bytes = Convert.FromBase64String(reposne.ToString());
File.WriteAllBytes("F:\file.exe", bytes);

我实际上正在使用RestSharp。

喜欢:

    public FileInfo DownloadFile(string downloadUrl)
    {
        RestClient rest = new RestClient();
        RestRequest request = new RestRequest(downloadUrl);
        byte[] downloadedfile = rest.DownloadData(request);
        string tempFilePath = Path.GetTempFileName();
        File.WriteAllBytes(tempFilePath, downloadedfile);
        return new FileInfo(tempFilePath);
    }

考虑不要为每个下载请求创建REST客户端。休息器还支持基本URL,以方便起见。

希望这就是您想要的。

I have tested your scenario using Java, Selenium and TestNG. Where you can save the file in the root folder directory
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileDownload {
    File folder;
    WebDriver driver;
    @SuppressWarnings("deprecation")
    @BeforeMethod
    public void setUp() {
        //a random folder will be created 88998-98565-09792-783727-826233
        folder = new File(UUID.randomUUID().toString());
        folder.mkdir();
        //Chrome Driver
        System.setProperty("webdriver.chrome.driver", "---Your Chrome Driver or chromedriver.exe URL;--");
        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<String, Object>();
        //When you click on download, it will ignore the popups
        prefs.put("profile.default_content_settings.popups", 0);
        prefs.put("download.default_directory", folder.getAbsolutePath());
        options.setExperimentalOption("prefs", prefs);
        DesiredCapabilities cap = DesiredCapabilities.chrome();
        cap.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(cap);
    }
    @Test
    public void downloadFileTest() throws InterruptedException{
        driver.get("https://www.win-rar.com/predownload.html?&L=0");
        driver.findElement(By.linkText("Download WinRAR")).click();
        /* Depending on your download speed you have to increase or decrease the sleep value, if you give less than download time it will give error as: java.lang.AssertionError: expected [true] but found [false] */
        Thread.sleep(5000);
        File listOfFiles[] = folder.listFiles();
        Assert.assertTrue(listOfFiles.length>0);
        for(File file: listOfFiles){
            Assert.assertTrue(file.length()>0);
        }
    }       
    @AfterMethod
    public void tearDown() {
        driver.quit();
        /* You can comment below "for loop": for testing purpose where you can see the folder and file download, if you uncomment it will delete the file and folder: useful for regression you wont end up having so many files in the root folder */
        for(File file: folder.listFiles()){
            file.delete();
        }
        folder.delete();
    }
}

如果您只是想下载文件,那么您真正需要的就是这样。

driver.FindElement(By.Id("download-button")).Click();

这将保存在您的浏览器的默认位置中。

或在JS执行程序中

WebElement element = driver.findElement(By.id("download-button"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

要转到特定位置,请尝试添加Chrome选项:

在C#

                ChromeOptions options = new ChromeOptions();
                options.AddArguments("--disable-extensions");
                options.AddArguments("disable-infobars");
                options.AddUserProfilePreference("download.default_directory", "My Path");
                 options.AddUserProfilePreference("profile.password_manager_enabled", false);
                options.AddUserProfilePreference("credentials_enable_service", false);
                _Driver = new ChromeDriver(@"DriverPath"), options);
                _wait = new WebDriverWait(_webDriver, TimeSpan.FromSeconds(10));
                _Driver.Manage().Window.Maximize();

作为最后的手段,只需以:

移动文件
    public class MoveMyFile
    {
        static void Main()
        {
            string sourceFile = @"C:MyFilePathfile.txt";
            string destinationFile = @"C:MyNewPathfile.txt";
            // Move my file to a new home!
            System.IO.File.Move(sourceFile, destinationFile);
        }
    }

最新更新