My New "Top Artists Last 7 Days" Widget
| Note Redux : I changed my approach, yet again. Scroll farther down to see the latest. Note : I changed my approach on this, so scroll down to see how I’m doing it now. I’ve been wanting a widget or an auto-post on the blog for a while that would show my most-listened-to bands over the previous week. Tumblr users have had something like this for a while, and there were efforts to do this for Wordpress before, but they either don’t seem to work with the latest versions of WP, or they only pulled top tracks (not artists), or they pulled album covers, instead of text. All of that is to say that I couldn’t find anything pre-made to use. So, I had to roll my own. I did so in about 10 minutes using the PHP Code Widget | http | response = http.read doc = REXML::Document.new response index = 0 File.open(ARGV[0], “w”) do | out | out.write(“<html><head>n”) out.write(“n”) out.write(“<body><ol>n”) doc.elements.each(“weeklyartistchart/artist”) do | artist | break if index == 5 out.write “<li>#{artist.elements[‘name’].text}, Plays: #{artist.elements[‘playcount’].text}</li>n” index += 1 end out.puts(“</ol></body></html>n”) end end [/ruby] and here’s the PHP that loads it: [php] <?php include(“/tmp/artists.html”); ?> [/php] That’s it. 11/26/2011 Update : Well, I’ve changed it again. I discovered that the RSS feed I was pulling is not updated with any sort of frequency. It certainly doesn’t represent the “last seven days” as it claims to. At any rate, it differs greatly from what Last.fm shows on the web. So I decided to grab the HTML and pull out the interesting bits. I wrote another Ruby script, this time using Hpricot to parse the HTML, which took about 10 minutes. So now, what you see on the right should be the current values for the “last seven days.” Here’s the latest script: [ruby] #!/usr/local/bin/ruby require ‘rubygems’ require ‘hpricot’ require ‘open-uri’ open(“http://www.last.fm/user/your-username-here/charts?rangetype=week&subtype=artists”) do | http | doc = Hpricot.parse(http.read) count = 0 File.open(ARGV[0], “w”) do | out | out.write(“<html><head>n”) out.write(“n”) out.write(“<body><ol>n”) doc.search(“td[@class=subjectCell]”).each do | subjectCell | break if count == 5 artistString = subjectCell.get_attribute(“title”) artistString =~ /^(.+), played (d+) times$/ artist = $1 playCount = $2 subjectCell.search(“a”).each do | a | url = a.get_attribute(“href”) url = “http://last.fm#{url}” str = “#{artist}, #{url}, #{playCount}” out.write “<li>#{artist}, Plays: #{playCount}</li>n” end count += 1 end out.puts(“</ol></body></html>n”) end end [/ruby] I’m hopeful this is the last change. |
This post is licensed under CC BY 4.0 by the author.