Skip to content

Instantly share code, notes, and snippets.

@jasperf
Forked from bueckl/wget
Created June 29, 2016 01:55
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save jasperf/17e9572b74f052b8fa12daca07ba8565 to your computer and use it in GitHub Desktop.
Save jasperf/17e9572b74f052b8fa12daca07ba8565 to your computer and use it in GitHub Desktop.
Wget examples
#Spider Websites with Wget – 20 Practical Examples
Wget is extremely powerful, but like with most other command line programs, the plethora of options it supports can be intimidating to new users. Thus what we have here are a collection of wget commands that you can use to accomplish common tasks from downloading single files to mirroring entire websites. It will help if you can read through the wget manual but for the busy souls, these commands are ready to execute.
1. Download a single file from the Internet
wget http://example.com/file.iso
2. Download a file but save it locally under a different name
wget ‐‐output-document=filename.html example.com
3. Download a file and save it in a specific folder
wget ‐‐directory-prefix=folder/subfolder example.com
4. Resume an interrupted download previously started by wget itself
wget ‐‐continue example.com/big.file.iso
5. Download a file but only if the version on server is newer than your local copy
wget ‐‐continue ‐‐timestamping wordpress.org/latest.zip
6. Download multiple URLs with wget. Put the list of URLs in another text file on separate lines and pass it to wget.
wget ‐‐input list-of-file-urls.txt
7. Download a list of sequentially numbered files from a server
wget http://example.com/images/{1..20}.jpg
8. Download a web page with all assets – like stylesheets and inline images – that are required to properly display the web page offline.
wget ‐‐page-requisites ‐‐span-hosts ‐‐convert-links ‐‐adjust-extension http://example.com/dir/file
Mirror websites with Wget
9. Download an entire website including all the linked pages and files
wget ‐‐execute robots=off ‐‐recursive ‐‐no-parent ‐‐continue ‐‐no-clobber http://example.com/
10. Download all the MP3 files from a sub directory
wget ‐‐level=1 ‐‐recursive ‐‐no-parent ‐‐accept mp3,MP3 http://example.com/mp3/
11. Download all images from a website in a common folder
wget ‐‐directory-prefix=files/pictures ‐‐no-directories ‐‐recursive ‐‐no-clobber ‐‐accept jpg,gif,png,jpeg http://example.com/images/
12. Download the PDF documents from a website through recursion but stay within specific domains.
wget ‐‐mirror ‐‐domains=abc.com,files.abc.com,docs.abc.com ‐‐accept=pdf http://abc.com/
13. Download all files from a website but exclude a few directories.
wget ‐‐recursive ‐‐no-clobber ‐‐no-parent ‐‐exclude-directories /forums,/support http://example.com
Wget for Downloading Restricted Content
Wget can be used for downloading content from sites that are behind a login screen or ones that check for the HTTP referer and the User Agent strings of the bot to prevent screen scraping.
14. Download files from websites that check the User Agent and the HTTP Referer
wget ‐‐refer=http://google.com ‐‐user-agent=”Mozilla/5.0 Firefox/4.0.1″ http://nytimes.com
15. Download files from a password protected sites
wget ‐‐http-user=labnol ‐‐http-password=hello123 http://example.com/secret/file.zip
16. Fetch pages that are behind a login page. You need to replace user and password with the actual form fields while the URL should point to the Form Submit (action) page.
wget ‐‐cookies=on ‐‐save-cookies cookies.txt ‐‐keep-session-cookies ‐‐post-data ‘user=labnol&password=123′ http://example.com/login.php
wget ‐‐cookies=on ‐‐load-cookies cookies.txt ‐‐keep-session-cookies http://example.com/paywall
Retrieve File Details with wget
17. Find the size of a file without downloading it (look for Content Length in the response, the size is in bytes)
wget ‐‐spider ‐‐server-response http://example.com/file.iso
18. Download a file and display the content on screen without saving it locally.
wget ‐‐output-document – ‐‐quiet google.com/humans.txt
wget
19. Know the last modified date of a web page (check the Last Modified tag in the HTTP header).
wget ‐‐server-response ‐‐spider http://www.labnol.org/
20. Check the links on your website to ensure that they are working. The spider option will not save the pages locally.
wget ‐‐output-file=logfile.txt ‐‐recursive ‐‐spider http://example.com
Also see: Essential Linux Commands
Wget – How to be nice to the server?
The wget tool is essentially a spider that scrapes / leeches web pages but some web hosts may block these spiders with the robots.txt files. Also, wget will not follow links on web pages that use the rel=nofollow attribute.
You can however force wget to ignore the robots.txt and the nofollow directives by adding the switch ‐‐execute robots=off to all your wget commands. If a web host is blocking wget requests by looking at the User Agent string, you can always fake that with the ‐‐user-agent=Mozilla switch.
The wget command will put additional strain on the site’s server because it will continuously traverse the links and download files. A good scraper would therefore limit the retrieval rate and also include a wait period between consecutive fetch requests to reduce the server load.
wget ‐‐limit-rate=20k ‐‐wait=60 ‐‐random-wait ‐‐mirror example.com
In the above example, we have limited the download bandwidth rate to 20 KB/s and the wget utility will wait anywhere between 30s and 90 seconds before retrieving the next resource.
Finally, a little quiz. What do you think this wget command will do?
wget ‐‐span-hosts ‐‐level=inf ‐‐recursive dmoz.org
@samverneck
Copy link

Translate in portuguese

#Spider Websites com o Wget - 20 exemplos práticos

O Wget é extremamente poderoso, mas, como na maioria dos outros programas de linha de comando, a infinidade de opções que ele aceita pode intimidar os novos usuários. Assim, o que temos aqui é uma coleção de comandos do wget que você pode usar para realizar tarefas comuns de baixar arquivos únicos para espelhar sites inteiros. Isso ajudará se você puder ler o manual do wget, mas para as almas ocupadas, esses comandos estão prontos para executar.

  1. Baixe um único arquivo da Internet
    Wget http://example.com/file.iso

  2. Baixe um arquivo, mas guarde-o localmente com um nome diferente
    Wget --output-document = filename.html example.com

  3. Baixe um arquivo e salve-o em uma pasta específica
    Wget - diretório-prefixo = pasta / subpasta example.com

  4. Resumir um download interrompido anteriormente iniciado pelo próprio Wget
    Wget --continue example.com/big.file.iso

  5. Baixe um arquivo, mas somente se a versão no servidor for mais recente do que sua cópia local
    Wget --continue --timetamping wordpress.org/latest.zip

  6. Baixe vários URLs com o wget. Coloque a lista de URLs em outro arquivo de texto em linhas separadas e passe para wget.
    Wget -input list-of-file-urls.txt

  7. Baixe uma lista de arquivos numerados sequencialmente de um servidor
    Wget http://example.com/images/{1..20}.jpg

  8. Baixe uma página da Web com todos os recursos - como folhas de estilo e imagens em linha - que são necessárias para exibir corretamente a página da Web offline.
    Wget --página-requisitos --span-hosts --convert-links --adjust-extension http://example.com/dir/file

Mirror sites com o Wget

  1. Baixe um site inteiro incluindo todas as páginas e arquivos vinculados
    Wget --executar robôs = desligado - recursivo - não-pai --continuar - não-clobber http://example.com/

  2. Baixe todos os arquivos MP3 de um subdiretor
    Wget --level = 1 --recursive --no-pai --accept mp3, MP3 http://example.com/mp3/

  3. Baixe todas as imagens de um site em uma pasta comum
    Wget - diretório-prefixo = arquivos / imagens - não-diretórios - recursivo - não-clobber - aceito jpg, gif, png, jpeg http://example.com/images/

  4. Baixe os documentos PDF de um site por meio de recursão, mas permaneça dentro de domínios específicos.
    Wget --mirror --domains = abc.com, files.abc.com, docs.abc.com --accept = pdf http://abc.com/

  5. Baixe todos os arquivos de um site, mas exclua alguns diretórios.
    Wget --recursive --no-clobber - não-pai --excluir-diretórios / fóruns, / support http://example.com

Wget para baixar conteúdo restrito

O Wget pode ser usado para baixar conteúdo de sites que estão por trás de uma tela de login ou aqueles que verificam o referente HTTP e as seqüências de caracteres do agente do usuário para evitar a raspagem da tela.

  1. Faça o download de arquivos de sites que verificam o User Agent e o HTTP Referer
    Wget --refer = http: //google.com --user-agent = "Mozilla / 5.0 Firefox / 4.0.1" http://nytimes.com

  2. Baixe arquivos de sites protegidos por senha
    Wget --http-user = labnol --http-password = hello123 http://example.com/secret/file.zip

  3. Procure páginas que estão por trás de uma página de login. Você precisa substituir o usuário e a senha pelos campos do formulário atual, enquanto o URL deve apontar para a página Enviar formulário (ação).
    Wget --cookies = on --save-cookies cookies.txt --keep-session-cookies --post-data 'user = labnol & password = 123' http://example.com/login.php
    Wget --cookies = on --load-cookies cookies.txt --keep-session-cookies http://example.com/paywall

Recuperar detalhes do arquivo com o wget

  1. Encontre o tamanho de um arquivo sem baixá-lo (procure o comprimento do conteúdo na resposta, o tamanho está em bytes)
    Wget --spider - server-response http://example.com/file.iso

  2. Baixe um arquivo e exiba o conteúdo na tela sem salvá-lo localmente.
    Wget --output-document - --quiet google.com/humans.txt

Wget
19. Conheça a última data modificada de uma página da Web (verifique a última marca modificada no cabeçalho HTTP).
Wget --server-response --spider http://www.labnol.org/

  1. Verifique os links em seu site para garantir que estejam funcionando. A opção spider não salvará as páginas localmente.
    Wget --output-file = logfile.txt --recursive --spider http://example.com

Consulte também: Comandos essenciais do Linux

Wget - Como ser bom com o servidor?

A ferramenta wget é essencialmente uma aranha que raspa / leeches páginas da web, mas alguns hosts da web podem bloquear essas aranhas com os arquivos robots.txt. Além disso, o wget não seguirá links em páginas da web que usam o atributo rel = nofollow.

No entanto, você pode forçar o wget a ignorar as diretrizes robots.txt e nofollow, adicionando o switch --execute robots = off a todos os seus comandos do wget. Se um host da Web está bloqueando pedidos do wget ao observar a seqüência do Agente do Usuário, você pode sempre falso com a opção --user-agent = Mozilla.

O comando wget colocará pressão adicional no servidor do site, pois irá percorrer continuamente os links e baixar arquivos. Um bom raspador, portanto, limitaria a taxa de recuperação e também inclui um período de espera entre solicitações de busca consecutivas para reduzir a carga do servidor.

Wget --limit-rate = 20k - wait = 60 --random-wait --mirror example.com

No exemplo acima, limitamos a taxa de largura de banda de download para 20 KB / s e o utilitário wget aguardará entre 30s e 90 segundos antes de recuperar o próximo recurso.

Finalmente, um pequeno questionário. O que você acha que esse comando do wget fará?
Wget --span-hosts - nivel = inf - recursive dmoz.org

@erm3nda
Copy link

erm3nda commented Jun 10, 2018

Reply to quiz:

Actually nothing just than save this funny error :-) :

403 Forbidden
Code: AccessDenied
Message: Access Denied
RequestId: 5BA2850D4232FCFE
HostId: i44Sds+OVPkQlEKOHa4LT1O0kVJ2+u2yhsrYNw+0raVWHBEOUEC5/2c0VsiUr4SHlREb8+L7vWY=
An Error Occurred While Attempting to Retrieve a Custom Error Document
Code: AccessDenied
Message: Access Denied

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment