How to download a file using the remote selenium webdriver?

前端 未结 5 994
清歌不尽
清歌不尽 2020-12-09 18:24

I am using a remote selenium webdriver to perform some tests. At some point, however, I need to download a file and check its contents.

I am using the

5条回答
  •  佛祖请我去吃肉
    2020-12-09 19:06

    This works for PHP php-webdriver in 2020 for Chrome:

    $downloaddir = "/tmp/";
    $host = 'http://ipaddress:4444/wd/hub';
    try {
        $options = new ChromeOptions();
        $options->setExperimentalOption("prefs",["safebrowsing.enabled" => "true", "download.default_directory" => $downloaddir]);
        $options->addArguments( array("disable-extensions",'safebrowsing-disable-extension-blacklist','safebrowsing-disable-download-protection') );
        $caps = DesiredCapabilities::chrome();
        $caps->setCapability(ChromeOptions::CAPABILITY, $options);
        $caps->setCapability("unexpectedAlertBehaviour","accept");
        $driver = RemoteWebDriver::create($host, $caps);
        $driver->manage()->window()->setPosition(new WebDriverPoint(500,0));
        $driver->manage()->window()->setSize(new WebDriverDimension(1280,1000));
        $driver->get("https://file-examples.com/index.php/sample-documents-download/sample-rtf-download/");
        sleep(1);
        $driver->findElement(WebDriverBy::xpath("//table//tr//td[contains(., 'rtf')]//ancestor::tr[1]//a"))->click();
        sleep(1);
        $driver->get('chrome://downloads/');
        sleep(1);
        // $inject = "return downloads.Manager.get().items_.filter(e => e.state === 'COMPLETE').map(e => e.filePath || e.file_path); ";
        $inject = "return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.querySelector('a').innerText;";
        $filename = $driver->executeScript(" $inject" );
        echo "File name: $filename
    "; $driver->executeScript( "var input = window.document.createElement('INPUT'); ". "input.setAttribute('type', 'file'); ". "input.hidden = true; ". "input.onchange = function (e) { e.stopPropagation() }; ". "return window.document.documentElement.appendChild(input); " ); $elem1 = $driver->findElement(WebDriverBy::xpath("//input[@type='file']")); $elem1->sendKeys($downloaddir.$filename); $result = $driver->executeAsyncScript( "var input = arguments[0], callback = arguments[1]; ". "var reader = new FileReader(); ". "reader.onload = function (ev) { callback(reader.result) }; ". "reader.onerror = function (ex) { callback(ex.message) }; ". "reader.readAsDataURL(input.files[0]); ". "input.remove(); " , [$elem1]); $coding = 'base64,'; $cstart = strpos( $result, 'base64,' ); if ( $cstart !== false ) $result = base64_decode(substr( $result, $cstart + strlen($coding) )); echo "File content:
    $result
    "; $driver->quit(); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; }

提交回复
热议问题