Skip to content

Instantly share code, notes, and snippets.

@Drowze
Last active March 22, 2020 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drowze/49778d60b76b7cf496e72d9ac3e4c4ad to your computer and use it in GitHub Desktop.
Save Drowze/49778d60b76b7cf496e72d9ac3e4c4ad to your computer and use it in GitHub Desktop.
Ruby script to scrap wallpapers from Wallhaven. Also provided a way to automatically use a downloaded wallpaper #wallhaven #ruby
require 'mechanize'
class WallHaven
BASE_URI = 'https://wallhaven.cc'
def initialize(limit: 24, human_download: false)
@agent = Mechanize.new
@limit = limit.to_i
@human_download = human_download
end
def download(endpoint)
url = "#{BASE_URI}#{endpoint}"
download_wallpapers(list_page: @agent.get(url))
end
private
def download_wallpapers(list_page:)
wallpaper_links(list_page: list_page).shuffle.first(@limit).map do |link|
download_wallpaper(wallpaper_link: link)
end
end
def wallpaper_links(list_page:)
list_page.links.select do |l|
l.href && l.href.match?('/w/')
end
end
def download_wallpaper(wallpaper_link:)
page = wallpaper_link.click
sleep rand(2..10) if @human_download
page.images_with(src: /full/).first.fetch.save
end
end
downloaded_wallpapers = WallHaven.new(limit: ARGV[1] || 24).download(ARGV[0])
#system("feh --randomize --bg-fill #{downloaded_wallpapers.sample} &")
@Drowze
Copy link
Author

Drowze commented Nov 16, 2017

use example:
ruby wallhaven.rb '/search?q="minimalism"&sorting=random&atleast=1920x1080' 1

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