Linux wget: ваш загрузчик командной строки
Wget — это открыто распостраняемая утилита для загрузки файлов из интернет.
Он поддерживает HTTP, FTP, HTTPS и другие протоколы, а также средство аутентификации и множество других опций.
Если вы пользователь Linux или Mac, WGET либо уже включен в пакет, который вы используете, либо это простой случай установки из любого репозитория, который вы предпочитаете, с помощью одной команды.
Как установить команду wget в Linux
Используйте команду apt / apt-get, если вы работаете в Ubuntu / Debian / Mint Linux:
$ sudo apt install wget
Пользователь Fedora Linux должен ввести команду dnf
$ sudo dnf install wget
Пользователь RHEL / CentOS / Oracle Linux должен ввести команду yum :
$ sudo yum install wget
Пользователь SUSE / OpenSUSE Linux должен ввести команду zypper:
$ zypper install wget
Пользователь Arch Linux должен ввести команду pacman:
$ sudo pacman -S wget
К сожалению, в Windows все не так просто (хотя не так сложно!).
Для запуска WGET вам необходимо скачать, распаковать и установить утилиту вручную.
Установите WGET в Windows 10
Загрузите классическую 32-разрядную версию 1.14 здесь или перейдите в эту коллекцию двоичных файлов Windows на сайте Eternal Bored здесь, чтобы получить более поздние версии и более быстрые 64-разрядные сборки.
Вот загружаемый zip-файл для 64-разрядной версии 1.2.
Если вы хотите иметь возможность запускать WGET из любого каталога в терминале, вам нужно будет узнать о переменных пути в Windows, чтобы решить, куда копировать новый исполняемый файл. Если вы это сделаете, то сможете сделать WGET командой, которую можно запускать из любого каталога в командной строке, это отдельная тема по настройке Windows.
Запуск WGET из любого места
Во-первых, нам нужно определить, куда копировать WGET.exe.
Мы собираемся переместить wget.exe в каталог Windows, который позволит запускать WGET из любого места.
После того, как вы загрузили wget.exe (или распаковали связанные с ним zip-файлы дистрибутива), откройте командный терминал, набрав «cmd» в меню поиска и запустите командную строку.
Во-первых, нам нужно выяснить, в каком каталоге это должно быть. В командную строку введите:
path
Вы должны увидеть что-то вроде этого:
Благодаря переменной окружения “Path” мы знаем, что нам нужно скопировать wget.exe в папку c:\Windows\System32.
Скопируйте WGET.exe в каталог System32 и перезапустите командную строку.
Если вы хотите проверить правильность работы WGET, перезапустите терминал и введите:
wget -h
Если вы скопировали файл в нужное место, вы увидите файл справки со всеми доступными командами.
Итак, вы должны увидеть что-то вроде этого:
Начнем работать с WGET
Мы будем работать в командной строке, поэтому давайте создадим каталог загрузок только для загрузок WGET.
Чтобы создать каталог, воспользуемся командой md («создать каталог»).
Перейдите в корневой каталог c: / и введите команду:
md wgetdown
Затем перейдите в новый каталог и введите «dir», и вы увидите (пустое) содержимое.
После того, как вы установили WGET и создали новый каталог, все, что вам нужно сделать, это изучить некоторые тонкости аргументов WGET, чтобы убедиться, что вы получаете то, что вам нужно.
Руководство Gnu.org WGET — особенно полезный ресурс для тех, кто действительно хочет узнать подробности.
Вот несколько советов, как извлечь из этого максимум пользы:
Linux wget примеры команд
Синтаксис:
wget url
wget [options] url
Давайте посмотрим на некоторые распространенные примеры команд Linux wget, синтаксис и использование.
WGET можно использовать для:
Скачать один файл с помощью wget
$ wget https://cyberciti.biz/here/lsst.tar.gz
Загрузить несколько файлов с помощью wget
$ wget https://cyberciti.biz/download/lsst.tar.gz ftp://ftp.freebsd.org/pub/sys.tar.gz ftp://ftp.redhat.com/pub/xyz-1rc-i386.rpm
Можно прочитать URL из файла
Вы можете поместить все URL в текстовый файл и использовать опцию -i, чтобы wget загрузил все файлы. Сначала создайте текстовый файл:
$ xed /temp/download.txt
Добавить список URL:
https://cyberciti.biz/download/lsst.tar.gz
ftp://ftp.freebsd.org/pub/sys.tar.gz
ftp://ftp.redhat.com/pub/xyz-1rc-i386.rpm
Введите команду wget следующим образом:
$ wget -i /temp/download.txt
Можно ограничить скорость загрузки
$ wget -c -o /temp/susedvd.log —limit-rate=50k ftp://ftp.novell.com/pub/suse/dvd1.iso
Используйте wget с сайтами, защищенными паролем
Вы можете указать http имя пользователя / пароль на сервере следующим образом:
$ wget —http-user=vivek —http-password=Secrete http://cyberciti.biz/vivek/csits.tar.gz
Другой способ указать имя пользователя и пароль — в самом URL.
$ wget ‘http://username:password@cyberciti.biz/file.tar.gz
Скачать все mp3 или pdf файлы с удаленного FTP сервера
$ wget ftp://somedom-url/pub/downloads/*.mp3
$ wget ftp://somedom-url/pub/downloads/*.pdf
Скачать сайт целиком
$ wget -r -k -l 7 -p -E -nc https://site.com/
Рассмотрим используемые параметры:
-r — указывает на то, что нужно рекурсивно переходить по ссылкам на сайте, чтобы скачивать страницы.
-k — используется для того, чтобы wget преобразовал все ссылки в скаченных файлах таким образом, чтобы по ним можно было переходить на локальном компьютере (в автономном режиме).
-p — указывает на то, что нужно загрузить все файлы, которые требуются для отображения страниц (изображения, css и т.д.).
-l — определяет максимальную глубину вложенности страниц, которые wget должен скачать (по умолчанию значение равно 5, в примере мы установили 7). В большинстве случаев сайты имеют страницы с большой степенью вложенности и wget может просто «закопаться», скачивая новые страницы. Чтобы этого не произошло можно использовать параметр -l.
-E — добавлять к загруженным файлам расширение .html.
-nc — при использовании данного параметра существующие файлы не будут перезаписаны. Это удобно, когда нужно продолжить загрузку сайта, прерванную в предыдущий раз.
По умолчанию wget загружает файл и сохраняет его с оригинальным именем в URL — в текущем каталоге.
Здесь я перечислил набор инструкций для WGET для рекурсивного зеркалирования вашего сайта, загрузки всех изображений, CSS и JavaScript, локализации всех URL-адресов (чтобы сайт работал на вашем локальном компьютере) и сохранения всех страниц как .html файл.
Чтобы скачать ваш сайт, выполните эту команду:
wget -r https://www.yoursite.com
Чтобы скачать сайт и локализовать все URL:
wget —convert-links -r https://www.yoursite.com
Чтобы создать полноценное оффлайн зеркало сайта:
wget —mirror —convert-links —adjust-extension —page-requisites —no-parent https://www.yoursite.com
Чтобы скачать сайт и сохранить файлы как .html:
wget —html-extension -r https://www.yoursite.com
Чтобы скачать все изображения в формате jpg с сайта:
wget -A «*.jpg» -r https://www.yoursite.com
Дополнительные сведения об операциях, связанных с конкретным типом файлов, можно найти в этой полезной ветке на Stack .
Установите другой пользовательский агент:
Некоторые веб-серверы настроены так, чтобы запрещать пользовательский агент WGET по умолчанию — по очевидным причинам экономии полосы пропускания. Вы можете попробовать изменить свой пользовательский агент, чтобы обойти это. Например, притворившись роботом Google:
wget —user-agent=»Googlebot/2.1 (+https://www.googlebot.com/bot.html)» -r https://www.yoursite.com
Wget режим «паук»:
Wget может получать страницы без их сохранения, что может быть полезной функцией, если вы ищете неработающие ссылки на веб-сайте. Не забудьте включить рекурсивный режим, который позволяет wget сканировать документ и искать ссылки для перехода.
wget —spider -r https://www.yoursite.com
Вы также можете сохранить это в файл журнала, добавив эту опцию:
wget —spider -r https://www.yoursite.com -o wget.log
wget -m -l 10 -e robots=off -p -k -E —reject-regex «wp» —no-check-certificate -U=«Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36» site-addr.com
Как найти неработающие ссылки на вашем сайте
wget —spider -r -nd -nv -H -l 2 -w 2 -o run1.log https://site.by
Наслаждайтесь использованием этого мощного инструмента, и я надеюсь, что вам понравился мой урок.
Wget is a free, open-source, command-line download manager that enables users to retrieve files from the internet using HTTP, HTTPS, and FTP protocols. Developed by the GNU Project, Wget is a powerful tool that allows users to download files, web pages, and entire websites with ease. Its primary function is to facilitate the non-interactive download of files, making it an essential utility for web developers, system administrators, and power users.
Wget’s primary advantage lies in its ability to resume broken downloads, which is particularly useful for large file transfers. It also supports HTTP cookies, proxy servers, and authentication, making it a versatile tool for downloading content from various sources. Additionally, Wget’s command-line interface allows for automation and scripting, making it a favorite among developers and system administrators.
Although Wget is primarily designed for Linux and Unix-like operating systems, its functionality and flexibility have made it a sought-after tool for Windows users as well. However, due to the differences in operating systems, installing Wget on Windows requires additional steps. Fortunately, with the right guidance, Windows users can also harness the power of Wget to manage their downloads efficiently. In this article, we will walk you through the process of installing Wget on Windows, making it accessible to users who want to take advantage of its features.
Installing Wget on Windows
Installing Wget on Windows is a straightforward process that requires downloading the GNU Wget package and placing it in the correct directory. Here’s a step-by-step guide to help you get started:
Step 1: Download GNU Wget for Windows
To begin, navigate to the official GNU Wget download page. This website provides pre-compiled binaries of Wget for Windows, making it easy to install and use.
Step 2: Select the Latest Version
On the download page, you’ll find multiple versions of GNU Wget for Windows. Look for the latest version and click on the corresponding `.exe` file to download it. The file name should be in the format `wget-<version>.exe`, where `<version>` is the version number. For example, if the latest version is 1.21.3, the file name would be wget64-1.21.3.exe:
Step 3: Place Wget in the System32 Folder
Once the download is complete, navigate to the folder where the .exe file is saved and copy it. Then, go to the C:\Windows\System32
folder (for 64-bit systems) or C:\Windows\SysWOW64
(for 32-bit systems) and paste the .exe file:
It’s essential to place the `wget.exe` file in the System32 folder because this directory is included in the system’s PATH environment variable. By placing the Wget Windows tutorial in this folder, you can execute it from anywhere in the Command Prompt or PowerShell without specifying the full path.
Step 4: Verify Wget Installation
To verify that Wget has been installed correctly, open the Command Prompt or PowerShell and type the following command:
wget -V
Press Enter to execute the command. If Wget has been installed successfully, you should see a message indicating the version number and a list of supported protocols, similar to this:
This confirms that Wget is installed and ready to use on your Windows system.
Explore the Blazing Fast Speed of Windows VPS!
Hosting a Windows VPS with Ultahost is now simpler and faster than ever. Experience ultra-fast SSD NVMe speeds with no interruptions or slowdowns.
Features of Wget
Wget’s primary advantage lies in its ability to resume broken downloads, which is particularly useful for large file transfers. It also supports HTTP cookies, proxy servers, and authentication, making it a versatile tool for downloading content from various sources. Additionally, Wget’s command-line interface allows for automation and scripting, making it a favorite among developers and system administrators.
Some of the key features of Wget include:
- Resuming broken downloads: Wget can resume downloads that were interrupted due to network issues or other errors.
- Support for HTTP cookies: Wget supports HTTP cookies, which allows it to download content from websites that require authentication.
- Proxy server support: Wget can use proxy servers to download content from the internet.
- Authentication support: Wget supports authentication protocols such as HTTP Basic and Digest.
- Command-line interface: Wget’s command-line interface allows for automation and scripting.
- Multi-threading: Wget can download multiple files simultaneously, making it faster than traditional download managers.
Troubleshooting Common Issues
If you encounter any issues during the installation process, here are some common solutions:
- Wget not recognized: Make sure that the wget.exe file is in the
C:\Windows\System32
folder (for 64-bit systems) orC:\Windows\SysWOW64
(for 32-bit systems). - Error message “wget is not recognized as an internal or external command”: Make sure that the
C:\Windows\System32
folder (for 64-bit systems) orC:\Windows\SysWOW64
(for 32-bit systems) is in the system’s PATH environment variable. - Wget not downloading files: Make sure that the URL is correct and that the file is available for download.
Wget Options and Flags
Wget has a wide range of options and flags that can be used to customize its behavior. Here are some common options and flags:
- -a: Append to the output file instead of overwriting it.
- -b: Run in the background.
- -c: Continue downloading a file that was interrupted.
- -d: Set the debug level.
- -e: Execute the specified command after the download is complete.
- -i: Read URLs from the specified file.
- -l: Specify the maximum depth of recursive downloads.
- -m: Mirror the specified website.
- -n: Specify the number of tries to retry a download.
- -o: Output the downloaded file to the specified file.
- -q: Quiet mode, suppress output.
- -r: Recursive download, which downloads all files and subdirectories.
- -s: Specify the maximum size of the output file.
- -t: Specify the number of tries to retry a download wget on Windows.
- -u: Specify the username for authentication.
- -v: Verbose mode, display detailed output.
- -w: Specify the wait time between retries.
Conclusion
Installing Wget on Windows is a straightforward process that requires downloading the GNU Wget package and placing it in the correct directory. The installation process involves downloading the latest version of Wget, placing the wget.exe file in the C:\Windows\System32 folder (for 64-bit systems) or C:\Windows\SysWOW64 (for 32-bit systems), and verifying the installation by running the wget -V command. With these simple steps, users can easily install Wget on their Windows system and start using it to download files and web pages from the internet.
By following the steps outlined in this guide, users can overcome the limitations of traditional download managers and take advantage of Wget’s advanced features, such as resuming broken downloads, supporting HTTP cookies, and authenticating with proxy servers. With Wget installed on their Windows system, users can automate downloads, mirror websites, and perform other tasks with ease, making it an essential tool for web developers, system administrators, and power users.
After completing these steps, you’ve successfully installed Wget on your Windows system and are now ready to develop robust applications. For optimal performance and smooth development, remember to follow best practices. consider using Ultahost Windows hosting. You get reliable and high-speed hosting tailored to your needs.
FAQ
What is wget?
wget is a free utility that allows you to download files from the web using HTTP, HTTPS, and FTP protocols. It is often used for retrieving files from the internet or mirroring entire websites.
Why would I want to install wget on Windows?
While Windows has built-in tools like PowerShell and Command Prompt for downloading files, wget offers more advanced features and options. It is particularly useful for automating downloads, handling complex file retrieval tasks, and mirroring websites.
Where can I download wget for Windows?
You can download the Windows version of wget from the official GNU site or other reputable sources like Chocolatey or Git for Windows.
How do I install wget using the installer?
- Download the wget installer executable from the GNU site.
- Run the installer and follow the on-screen instructions.
- By default, the installer should add wget to your system PATH. If not, you may need to do this manually (see below).
How do I verify that wget is installed correctly?
Open Command Prompt and type wget –version. You should see version information if wget is installed correctly. If you receive an error or command not found message, ensure wget is correctly installed and added to your PATH.
Are there alternatives to wget on Windows?
Yes, there are several alternatives including curl (which is built into Windows 10 and later), aria2, and tools provided by Git for Windows.
Where can I find additional documentation or help for wget?
The official wget manual and documentation can be found on the GNU website. Online forums and communities also offer valuable tips and troubleshooting help.
Windows binaries of GNU Wget 1.21.4
This is a command-line tool that can be used to retrieve files via the HTTP, HTTPS, and FTP protocols.
GNU Wget is a free software package that allows users to retrieve files through the most commonly used Internet protocols,
including HTTP, HTTPS, FTP, and FTPS. As a non-interactive command-line tool,
it can be easily integrated into scripts, cron jobs, and terminals.
How to use wget
To learn how to use Wget, please refer to the official GNU Wget manual by clicking the link below.
https://www.gnu.org/software/wget/manual/wget.html
Build Environment
Wget has been built using GitHub Actions and cross-compiled with mingw64 on Ubuntu, using GNU/gcc 9.3.
It is completely safe to use and free from viruses.
All the necessary libraries have been statically linked, so there is no need to use any third-party DLL.
Wget features
The Windows version of Wget includes all features of Wget except for NLS (the multi-language version).
GnuTLS version:
+cares +digest +gpgme +https +ipv6 +iri +large-file +metalink -nls +ntlm +opie +psl +ssl/gnutls
OpenSSL version:
+cares +digest +gpgme +https +ipv6 +iri +large-file +metalink -nls +ntlm +opie +psl +ssl/openssl
Local Build
To build Wget for Windows on WSL 1 or 2 (Debian/Ubuntu), please follow these steps.
sudo apt-get install -y mingw-w64 mingw-w64-tools mingw-w64-i686-dev gcc sudo apt-get install -y make m4 pkg-config automake gettext cd /tmp git clone https://github.com/webfolderio/wget-windows.git cd wget-windows ./build.sh
Что такое wget?
Это утилита командной строки для получения файлов с использованием HTTP, HTTPS и FTP протоколов.
Как установить wget на компьютер с ОС Windows?
Вариант, которым пользуюсь сам, это скачать архив с уже скомпилированными бинарными файлами GNU Wget 0
После того как скачали архив, в любом месте создаём папку wget, например в C:\Program Files\wget
и в эту папку распаковываем всё содержимое скачанного архива.
Чтобы программа свободно вызывалась отовсюду нужно добавить путь в переменную среды Path операционной системы Windows. Для этого заходим в Панель управления > Система
В зависимости какая разрядность у вашей установленной Windows, запускайте 32-битную либо 64-битную версию программы, wget либо wget64 соответственно.
Обратите внимание, что начиная с версии wget 1.20 прекращена поддержка Windows XP.
Примеры команд для wget:
Скачать файл с докачкой по протоколу http
wget -c http://ftp.byfly.by/pub/CentOS/8/isos/x86_64/CentOS-8.3.2011-x86_64-boot.iso
Скачать файл по протоколу https
wget --no-check-certificate https://www.linux.org.ru/images/7626/original.jpg
Скачать файл с докачкой по протоколу ftp
wget -c ftp://ftp.byfly.by/pub/CentOS/8/isos/x86_64/CentOS-8.3.2011-x86_64-boot.iso
Скачать с докачкой файлы по списку ссылок (в текстовом файле)
wget -c -i spisok.txt
Скачать рекурсивно указанный сайт
wget -rkx URL
Описание прочих команд смотрите во встроенной в программу помощи
wget -h GNU Wget 1.20.3, программа для загрузки файлов из сети в автономном режиме. Использование: wget [ПАРАМЕТР]... [URL]... Обязательные аргументы для длинных параметров являются обязательными и для коротких параметров. Запуск: -V, --version показать версию Wget и завершить работу -h, --help показать эту справку -b, --background после запуска перейти в фоновый режим -e, --execute=КОМАНДА выполнить команду в стиле <.wgetrc> Журналирование и входной файл: -o, --output-file=ФАЙЛ записывать сообщения в ФАЙЛ -a, --append-output=ФАЙЛ дописывать сообщения в конец ФАЙЛА -d, --debug показать много отладочной информации -q, --quiet ничего не выводить -v, --verbose показывать подробные сведения (по умолчанию) -nv, --no-verbose отключить вывод подробных сведений (не полностью) --report-speed=ТИП единицы измерения пропускной способности определить ТИПОМ. ТИП может быть равно bits -i, --input-file=ФАЙЛ загрузить URL-ы согласно локальному или внешнему ФАЙЛУ --input-metalink=ФАЙЛ скачать файлы, перечисленные в локальном ФАЙЛЕ Metalink -F, --force-html считать, что входной файл - HTML -B, --base=URL считать, что ссылки из входного файла (-i -F) указаны относительно URL --config=ФАЙЛ задать файл настроек --no-config не читать файлы настроек --rejected-log=ФАЙЛ протоколировать причины отброса URL в ФАЙЛ Загрузка: -t, --tries=ЧИСЛО установить ЧИСЛО повторных попыток (0 без ограничения) --retry-connrefused повторять, даже если в подключении отказано -O, --output-document=ФАЙЛ записывать документы в ФАЙЛ -nc, --no-clobber пропускать загрузки, которые приведут к загрузке уже существующих файлов (и их перезаписи) --no-netrc don't try to obtain credentials from .netrc -c, --continue возобновить загрузку частично загруженного файла --start-pos=СМЕЩЕНИЕ начинать загрузку со СМЕЩЕНИЯ (считается с 0) --progress=ТИП выбрать тип индикатора выполнения --show-progress показывать индикатор выполнения в любом режиме подробности -N, --timestamping не загружать повторно файлы, только если они не новее, чем локальные --no-use-server-timestamps не использовать проверку if-modified-since для запросов в режиме учёта меток времени --no-use-server-timestamps не устанавливать метку времени локальному файлу, полученную с сервера -S, --server-response вывод ответа сервера --spider ничего не загружать -T, --timeout=СЕКУНДЫ установка значений всех тайм-аутов равными числу СЕКУНД --dns-servers=АДРЕСА список запрашиваемых серверов DNS (через запятую) --bind-dns-address=АДРЕС привязать определитель DNS к АДРЕСУ (имя компьютера или IP) локального компьютера --dns-timeout=СЕК установка тайм-аута поиска в DNS в СЕК --connect-timeout=СЕК установка тайм-аута подключения в СЕК --read-timeout=СЕК установка тайм-аута чтения в СЕК -w, --wait=СЕКУНДЫ пауза в СЕКУНДАХ между загрузками --waitretry=СЕКУНДЫ пауза в 1..СЕКУНДЫ между повторными попытками загрузки --random-wait пауза в 0.5*WAIT...1.5*WAIT секунд между загрузками --no-proxy явно выключить прокси -Q, --quota=ЧИСЛО установить величину квоты загрузки в ЧИСЛО --bind-address=АДРЕС привязать АДРЕС (имя компьютера или IP) локального компьютера --limit-rate=СКОРОСТЬ ограничить СКОРОСТЬ загрузки --no-dns-cache отключить кэширование DNS-запросов --restrict-file-names=ОС использовать в именах файлов символы, допустимые в ОС --ignore-case игнорировать регистр при сопоставлении файлов и/или каталогов -4, --inet4-only подключаться только к адресам IPv4 -6, --inet6-only подключаться только к адресам IPv6 --prefer-family=СЕМЕЙСТВО подключаться сначала к адресам указанного семейства (может быть IPv6, IPv4 или ничего) --user=ПОЛЬЗОВАТЕЛЬ установить и ftp- и http-пользователя в ПОЛЬЗОВАТЕЛЬ --password=ПАРОЛЬ установить ftp- и http-пароль в ПАРОЛЬ --ask-password запрашивать пароли --use-askpass=КОМАНДА указать обработчик мандатов для запроса имени пользователя и пароля. Если КОМАНДА не указана, то используется переменная окружения WGET_ASKPASS или SSH_ASKPASS. --no-iri выключить поддержку IRI --local-encoding=КДР использовать КДР как локальную кодировку для IRI --remote-encoding=КДР использовать КДР как удалённую кодировку по умолчанию --unlink удалить файл перед затиранием --keep-badhash оставлять файлы с неправильными контрольными суммами (добавляя .badhash) --metalink-index=НОМЕР порядковый НОМЕР metaurl Metalink application/metalink4+xml --metalink-over-http использовать метаданные Metalink из заголовка ответов HTTP --preferred-location предпочитаемое расположение ресурсов Metalink Каталоги: -nd, --no-directories не создавать каталоги -x, --force-directories принудительно создавать каталоги -nH, --no-host-directories не создавать каталоги как на узле --protocol-directories использовать имя протокола в каталогах -P, --directory-prefix=ПРЕФИКС сохранять файлы в ПРЕФИКС/.. --cut-dirs=ЧИСЛО игнорировать ЧИСЛО компонентов удалённого каталога Параметры HTTP: --http-user=ПОЛЬЗОВ. установить http-пользователя в ПОЛЬЗОВАТЕЛЬ --http-password=ПАРОЛЬ установить http-пароль в ПАРОЛЬ --no-cache отвергать кэшированные сервером данные --default-page=ИМЯ изменить имя страницы по умолчанию (обычно это ) -E, --adjust-extension сохранять документы HTML/CSS с надлежащими расширениями --ignore-length игнорировать поле заголовка --header=СТРОКА вставить СТРОКУ между заголовками --compression=TYPE choose compression, one of auto, gzip and none. (default: none) --max-redirect максимально допустимое число перенаправлений на страницу --proxy-user=ПОЛЬЗОВ. установить ПОЛЬЗОВАТЕЛЯ в качестве имени пользователя для прокси --proxy-password=ПАРОЛЬ установить ПАРОЛЬ в качестве пароля для прокси --referer=URL включить в HTTP-запрос заголовок --save-headers сохранять HTTP-заголовки в файл -U, --user-agent=АГЕНТ идентифицировать себя как АГЕНТ вместо Wget/ВЕРСИЯ --no-http-keep-alive отключить поддержание активности HTTP (постоянные подключения) --no-cookies не использовать кукисы --load-cookies=ФАЙЛ загрузить кукисы из ФАЙЛА перед сеансом --save-cookies=ФАЙЛ сохранить кукисы в ФАЙЛ после сеанса --keep-session-cookies загрузить и сохранить кукисы сеанса (непостоянные) --post-data=СТРОКА использовать метод POST; отправка СТРОКИ в качестве данных --post-file=ФАЙЛ использовать метод POST; отправка содержимого ФАЙЛА --method=HTTPMethod использовать метод в заголовке --body-data=СТРОКА отправка СТРОКИ в качестве данных; ДОЛЖЕН быть указан параметр --method --body-file=ФАЙЛ отправка содержимого ФАЙЛА; ДОЛЖЕН быть указан параметр --method --content-disposition учитывать заголовок Content-Disposition при выборе имён для локальных файлов (ЭКСПЕРИМЕНТАЛЬНЫЙ) --content-on-error выводить принятые данные при ошибках сервера --auth-no-challenge отправлять информацию об аутентификации Basic HTTP не дожидаясь первого ответа сервера Параметры HTTPS (SSL/TLS): --secure-protocol=PR choose secure protocol, one of auto, SSLv2, SSLv3, TLSv1, TLSv1_1, TLSv1_2 and PFS --https-only переходить только по безопасным ссылкам HTTPS --no-check-certificate не проверять сертификат сервера --certificate=FILE файл сертификата пользователя --certificate-type=ТИП тип сертификата пользователя: PEM или DER --private-key=ФАЙЛ файл секретного ключа --private-key-type=ТИП тип секретного ключа: PEM или DER --ca-certificate=ФАЙЛ файл с набором CA --ca-directory=КАТ каталог, в котором хранится список CA --crl-file=ФАЙЛ файл с набором CRL --pinnedpubkey=ФАЙЛ/ХЭШИ Файл с открытым ключом (PEM/DER) или любое количество хэшей sha256 в виде base64, начинающихся с и разделённых <;>, по которым проверяется ответный узел Параметры HSTS: --no-hsts отключить HSTS --hsts-file путь к базе данных HSTS (заменит значение по умолчанию) Параметры FTP: --ftp-user=ПОЛЬЗОВАТЕЛЬ установить ftp-пользователя в ПОЛЬЗОВАТЕЛЬ --ftp-password=ПАРОЛЬ установить ftp-пароль в ПАРОЛЬ --no-remove-listing не удалять файлы <.listing> --no-glob выключить маски для имён файлов FTP --no-passive-ftp отключить <пассивный> режим передачи --preserve-permissions сохранять права доступа удалённых файлов --retr-symlinks при рекурсии загружать файлы по ссылкам (не каталоги) Параметры FTPS: --ftps-implicit безусловно использовать FTPS (порт по умолчанию - 990) --ftps-resume-ssl возобновлять сеанс SSL/TLS, начатый в канале управления, при открытии канала данных --ftps-clear-data-connection шифровать только канал управления; данные не шифруются --ftps-fallback-to-ftp вернуться к FTP, если FTPS не поддерживается сервером Параметры WARC: --warc-file=ФАЙЛ записать данные запроса/ответа в файл .warc.gz --warc-header=СТРОКА вставить СТРОКУ в запись warcinfo --warc-max-size=ЧИСЛО максимальный размер файлов WARC равен ЧИСЛУ --warc-cdx записать индексные файлы CDX --warc-dedup=ФАЙЛ не сохранять записи, перечисленные в файле CDX --no-warc-compression не сжимать файлы WARC с помощью GZIP --no-warc-digests не вычислять дайджесты SHA1 --no-warc-keep-log не сохранять файл журнала в записи WARC --warc-tempdir=КАТАЛОГ расположение для временных файлов, создаваемых процедурой записи WARC Рекурсивная загрузка: -r, --recursive включение рекурсивной загрузки -l, --level=ЧИСЛО глубина рекурсии (inf и 0 - бесконечность) --delete-after удалять локальные файлы после загрузки -k, --convert-links делать ссылки локальными в загруженном HTML или CSS --convert-file-only преобразовывать только файловую часть URL (базовую часть имени) --backups=N перед записью файла X, ротировать до N резервных файлов -K, --backup-converted перед преобразованием файла X делать резервную копию в виде X.orig -m, --mirror короткий параметр, эквивалентный -N -r -l inf --no-remove-listing -p, --page-requisites загрузить все изображения и проч., необходимые для отображения HTML-страницы --strict-comments включить строгую (SGML) обработку комментариев HTML Разрешения/запреты при рекурсии: -A, --accept=СПИСОК список разрешённых расширений через запятую -R, --reject=СПИСОК список запрещённых расширений, разделённых запятыми. --accept-regex=РЕГВЫР регулярное выражение для разрешённых URL --reject-regex=РЕГВЫР регулярное выражение для запрещённых URL --regex-type=ТИП тип регулярного выражения (posix|pcre) -D, --domains=СПИСОК список разрешённых доменов, через запятую --exclude-domains=СПИСОК список запрещённых доменов, через запятую --follow-ftp следовать по ссылкам FTP в HTML-документах --follow-tags=СПИСОК список используемых тегов HTML, через запятую --ignore-tags=СПИСОК список игнорируемых тегов HTML, через запятую -H, --span-hosts заходить на чужие узлы при рекурсии -L, --relative следовать только по относительным ссылкам -I, --include-directories=СПИСОК список разрешённых каталогов --trust-server-names использовать имя, указанное в перенаправляющем URL, в качестве последнего компонента. -X, --exclude-directories=СПИСОК список исключаемых каталогов -np, --no-parent не подниматься в родительский каталог
Most users will download files onto their PC using their web browser. There’s a problem with this method, however—it’s not particularly efficient. If you need to pause your download, or if you’ve lost your connection, you’ll probably need to start your download again from scratch. You may also be working with Python or other code at the command line and want to download directly from the command prompt.
That’s where tools like Wget come in. This command line tool has a number of useful features, with support for recursive downloads and download resumption that allows you to download single files (or entire websites) in one go.
Wget is popular on Linux and other Unix-based operating systems, but it’s also available for Windows users. Below, we’ll explain how to install and use Wget to download any content you want online from your Windows command line.
Installing GNU Wget on Windows
Wget (in name, at least) is available on Windows 10 and 11 via the PowerShell terminal. However, this version of Wget isn’t the same as the GNU Wget tool that you’d use on a Linux PC. Instead, this version is simply an alias for a PowerShell command called Invoke-WebRequest.
Invoke-WebRequest is Wget-like in what it does, but it’s a completely different tool that’s much more difficult to use and understand. Instead, you’ll be better served by installing Wget for Windows, a compiled version of the same tool available for Linux users, using the steps below.
1. Download the Wget for Windows setup file from the Wget website. You’ll need to do this using your web browser.
Get Tom’s Hardware’s best news and in-depth reviews, straight to your inbox.
2. Run the Wget for Windows installer file. Once the Wget setup file has finished downloading, run the setup file and follow the on-screen instructions to complete the installation.
3. Update the Wget.exe file (optional). The Wget installer is packaged with a fairly old version of the Wget binary. If you run into difficulties downloading files because of SSL certificate errors, you should download the latest wget.exe for your architecture from this website and save it to your Wget installation directory (typically C:\Program Files (x86)\GnuWin32\bin). This step is optional, but highly recommended.
4. Open the Start menu, search for environment variables, and click Open. Once the installation is finished, use the search tool in the Start menu to search for environment variables, then click Open. You’ll need to do this to allow you to use the ‘wget’ command from the command line without referencing its location every time you wish to run it.
5. Click Environment Variables in the System Properties window.
6. Select Path and click Edit under System or User variables.
7. Click the New button and type in the directory for the Wget for Windows binary (.exe) file. By default, this should be C:\Program Files (x86)\GnuWin32\bin.
8. Save your changes. When you’re finished, click OK in each menu and exit System Properties.
9. Open the Start menu, type cmd, and press Open. This will launch a new command prompt window. You can also use the newer Terminal app, as long as you switch to using a command prompt shell.
10. Type wget —version and press Enter. If Wget was installed correctly, you should see the GNU Wget version returned in the command prompt window.
If you want to run Wget from a PowerShell terminal instead, you’ll need to run the file from its installation directory directly (eg. C:\Program Files (x86)\GnuWin32\bin\wget.exe).
Downloading Files with Wget
Once you’ve installed GNU Wget and you’ve configured the environment variables to be able to launch it correctly, you’ll be able to use it to start downloading files and webpages.
We’ve used an example domain and file path in our examples below. You’ll need to replace this with the correct path to the file (or files) that you want to download.
- Type wget -h to see a full list of commands. This will give you the full list of options that you can use with Wget.
wget -h
- Download a single file using wget <url>. Replace <url> with the path to a file on an HTTP, HTTPS, or FTP server. You can also refer to a website domain name or web page directly to download that specific page (without any of its other content).
wget example.com
- Save with a different filename using -O. Using the -O option, you’ll be able to save the file with a different filename. For example, wget -O <filename> <url>, where <filename> is the filename you’ve chosen.
wget -O example.html example.com
- Save to a different directory using -P. If you want to save to another directory than the one you’re currently in, use the -P option. For example, wget -P <path> <url>.
wget -P C:\folder example.com
- Use —continue or -c to resume files. If you want to resume a partial download, use the -c option to resume it, as long as you’re in the same directory. For example, wget -c <url>.
wget -c example.com
- Download multiple files in sequence. If you want to download several files, add each URL to your Wget command. For example, wget <url1> <url2> etc.
wget example.com tomshardware.com
- Download multiple files using a text file with -i. Using the -i option, you can refer to a text file that contains a list of URLs to download a large number of files. Assuming that each URL is on a new line, Wget will download the content from each URL in sequence. For example, wget -i <file.txt> <url>.
wget -i urls.txt
- Limit download speeds using —limit-rate. If you want to limit your bandwidth usage, you can cap the download speeds using the —limit-rate option. For example, wget —limit-rate=1M <url> would limit it to 1 megabyte per second download speeds, while wget —limit-rate=10K <url> would limit it to 10 kilobytes per second.
wget —limit-rate=10K example.com
- Use -w or –wait to set a pause period after each download. If you’re downloading multiple files, using -w can help to spread the requests you make and help to limit any chance that your downloads are blocked. For example, wget -w 10 <url1> <url2> for a 10 second wait.
wget -w 10 example.com tomshardware.com
- Set a retry limit using -t or —tries. If a download fails, wget will use the -t value to determine how many times it’ll attempt it again before it stops. The default value is 20 retries. If the file is missing, or if the connection is refused, then this value is ignored and Wget will terminate immediately.
wget -t 5 example.com
- Save a log using -o or -a. You can save your log data to a text file using -o (to always create a new log file) or -a (to append to an existing file). For example, wget -o <file.txt> <url>.
- Bypass SSL errors using —no-check-certificate. If you’re having trouble downloading from a web server with an SSL certificate and you’ve already updated your Wget installation, bypass the SSL certificate check completely using —no-check-certificate to allow the download (in most cases). You should only do this for downloads from locations that you completely trust. For example, wget —no-check-certificate example.com.
wget —no-check-certificate https://example.com
Make sure to use the wget -h or wget —help command to view the full list of options that are available to you. If you run into trouble with Wget, make sure to limit the number of retries you make and set a wait limit for each download you attempt.
Using Wget for Recursive Downloads
One of Wget’s most useful features is the ability to download recursively. Instead of only downloading a single file, it’ll instead try to download an entire directory of related files.
For instance, if you specify a web page, it’ll download the content attached to that page (such as images). Depending on the recursive depth you choose, it can also download any pages that are linked to it, as well as the content on those pages, any pages that are linked on those pages, and so on.
Theoretically, Wget can run with an infinite depth level, meaning it’ll never stop trying to go further and deeper with the content it downloads. However, from a practical point of view, you may find that most web servers will block this level of scraping, so you’ll need to tread carefully.
- Type wget -r or wget —recursive to download recursively. By default, the depth level is five. For example, wget -r <url>.
wget -r tomshardware.com
- Use -l or –level to set a custom depth level. For example, wget -r -l 10 <url>. Use wget -r -l inf <url> for an infinite depth level.
wget -r -l 10 tomshardware.com
- Use -k to convert links to local file URLs. If you’re scraping a website, Wget will automatically convert any links in HTML to point instead to the offline copy that you’ve downloaded. For example, wget -r -k <url>.
wget -r -k tomshardware.com
- Use -p or —page-requisites to download all page content. If you want a website to fully download so that all of the images, CSS, and other page content is available offline, use the -p or —page-requisites options. For example, wget -r -p <url>.
wget -r -p tomshardware.com
For a full list of options, make sure to use the wget —h command. You should also take care to respect any website that you’re actively downloading from and do your best to limit server loads using wait, retry, and depth limits.
If you run into difficulties with downloads because of SSL certificate errors, don’t forget to update your Wget binary file (wget.exe) with the latest version.