Register now and start sharing your code snippets.
-->

How to automatically ping search engines when your sitemap has changed

Ruby posted 2 months ago by christian

I prefer letting cron update sitemaps in the background, and at the end of the script I ping search engines to let them know it’s been updated:

   1  # Recreate sitemap goes here
   2  
   3  # Let search engines know about the update
   4  [ "http://www.google.com/webmasters/tools/ping?sitemap=http://xxx/sitemap.xml",
   5    "http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=http://xxx/sitemap.xml",
   6    "http://submissions.ask.com/ping?sitemap=http://xxx/sitemap.xml",
   7    "http://webmaster.live.com/ping.aspx?siteMap=http://xxx/sitemap.xml" ].each do |url|
   8    open(url) do |f|
   9      if f.status[0] == "200"
  10        puts "Sitemap successfully submitted to #{url}"      
  11      else
  12        puts "Failed to submit sitemap to #{url}"
  13      end
  14    end
  15  end
  16  

More about sitemaps: http://en.wikipedia.org/wiki/Sitemaps

Tagged sitemap, ruby, ping, search, google

How to optimize your MephistoBlog powered site's search engine ranking (SEO for MephistoBlog)

Plain Text posted 4 months ago by christian

At Aktagon we use MephistoBlog as CMS , and I couldn’t find any information on how to SEO optimize MephistoBlog on Google, so I’m sharing my notes here.

This tip shows you how to make your pages more search engine friendly.

First, add the title tag, plus the meta description and keywords tags to your layout’s Liquid template , as shown here:

   1  <meta name="description" content="{% if article %} {{ article.excerpt }}  {% else %} YOUR DEFAULT SITE DESCRIPTION {% endif %}" />
   2  	<meta name="keywords" content="{% if article %} {% for tag in article.tags %}{{ tag }}, {% endfor %} {% endif %} YOUR DEFAULT KEYWORDS" />
   3  	<title>{% if article %} {{ article.title }} &raquo; {{ site.title }} {% else %} {{ site.title }} &raquo; {{ site.subtitle }} {% endif %}</title>

Remember to update the default description and keywords in the meta tags’ body.

Now, whenever you publish an article, simply add an excerpt and some tags to it. The excerpt is used as the meta description and the article’s tags as the meta keywords, both make Google a bit happier, but the description is by far the more important.

Tagged seo, mephistoblog, meta, google, search, keywords

How to track user actions and custom events with Google Analytics and jQuery

JavaScript posted 5 months ago by christian

This is a customization of Rebecca Murphey’s script:

   1  $('a').each(function() {
   2  	var $a = $(this);
   3  	var href = $a.attr('href');
   4  	
   5  	if(typeof pageTracker == 'undefined') { return; }
   6  
   7  	// Link is external
   8  	if (href.match(/^http/) && !href.match(document.domain)) {
   9  		$a.click(function() {
  10  			pageTracker._trackPageview('/external/' + href);
  11  		});
  12  	} else {
  13  		$a.click(function() {
  14  			pageTracker._trackPageview('/internal' + href);
  15  		});
  16  	}
  17  });

Note that clicks are shown as page views in reports, so you should exclude them from all reports. A future version of Google Analytics will allow you to track events, such as mouse clicks, without affecting page view reporting, see this page on the new event tracking beta feature for more information.

Tagged jquery, google, analytics, track, click

How to exclude your own traffic from Google Analytics reports and other JavaScript based analytics software

Ruby posted 5 months ago by christian

Option 1: Changing your browser’s user agent

Open the about:config page in Firefox by typing about:config in the address bar and pressing enter. Now change the general.useragent.extra.firefox setting to an easily identifiable string, for example the following:

   1  Firefox/3.0 disable-tracking

Then in your code check that the user-agent string doesn’t contain disable-tracking>

   1  <% if !request.user_agent.include?('disable-tracking') %>
   2  TRACKING CODE GOES HERE
   3  <% end %>

Option 2:

Use one of Google Analytics native ways of excluding traffic from certain domains, IPs, user-agents or users having a specific browser cookie.

Tagged google, analytics, tracking, exclude, traffic

Scraping Google search results with Scrubyt and Ruby

Ruby posted about 1 year ago by christian

Note that these instructions don’t work with the latest Scrubyt version…

Scrubyt is a Ruby library that allows you to easily scrape the contents of any site.

First install Scrubyt:

   1  $ sudo gem install mechanize hpricot parsetree ruby2ruby scrubyt

You also need to install ReadLine version 3.6.3:

   1  sudo gem install -v 3.6.3 RubyInline

If you install the wrong RubyInline version or have multiple versions installed, you’ll get the following error:

   1  /usr/lib/ruby/1.8/rubygems.rb:207:in `activate': can't activate RubyInline (= 3.6.3), already activated RubyInline-3.6.6] (Gem::Exception)
   2         from /usr/lib/ruby/1.8/rubygems.rb:225:in `activate'
   3         from /usr/lib/ruby/1.8/rubygems.rb:224:in `each'
   4         from /usr/lib/ruby/1.8/rubygems.rb:224:in `activate'
   5         from /usr/lib/ruby/1.8/rubygems/custom_require.rb:32:in `require'
   6         from t2:2

To fix it first uninstall the latest version, and keep only version 3.6.3:

   1  sudo gem uninstall RubyInline
   2  
   3  Select RubyGem to uninstall:
   4   1. RubyInline-3.6.3
   5   2. RubyInline-3.6.6
   6   3. All versions
   7  > 2

Scraping Google search results

Then run this to Scrape the first two pages of the Google results for ruby:

   1  require 'rubygems'
   2  require 'scrubyt'
   3  
   4  # See http://scrubyt.org/example-specification-from-the-page-known-issues-and-pitfalls/
   5  
   6  # Create a learning extractor
   7  data = Scrubyt::Extractor.define do
   8    fetch('http://www.google.com/')
   9    fill_textfield 'q', 'ruby'
  10    submit
  11    
  12    # Teach Scrubyt what we want to retrieve
  13    # In this case we want Scruby to find all search results
  14    # and "Ruby Programming Language" happens to be the first 
  15    # link in the result list. Change "Ruby Programming Language" 
  16    # to whatever you want Scruby to find.
  17    link do
  18      name  "Ruby Programming Language"
  19      url   "href", :type => :attribute
  20    end
  21    
  22    # Click next until we're on the second page.
  23    next_page "Next", :limit => 2
  24  end
  25  
  26  # Print out what Scruby found
  27  puts data.to_xml 
  28  
  29  puts "Your production scraper has been created: data_extractor_export.rb."
  30  
  31  # Export the production version of the scraper
  32  data.export(__FILE__)

Learning Extractor vs Production extractor

Note that this example uses the Learning Extractor functionality of Scrubyt.

The production extractor is generated with the last line:

   1  data.export(__FILE__)

If you open the production extractor in an editor you’ll see that it uses XPath queries to extract the content:

   1  link("/html/body/div/div/div/h2", { :generalize => true }) do
   2      name("/a[1]")
   3      url("href", { :type => :attribute })
   4    end

Finding the correct XPath

The learning mode is pretty good at finding the XPath of HTML elements, but if you have difficulties getting Scrubyt to extract exactly what you want, simply install Firebug and use the Inspect feature to select the item you want to extract the value from. Then right-click on it in the Firebug window and choose Copy XPath.

Note that there’s a gotcha when copying the XPath of an element with Firebug. Firebug uses Firefox’s internal and normalized DOM model, which might not match match the real-world HTML structure. For example the tbody tag is usually added by Firefox/Firebug, and should be removed if it isn’t in the HTML.

Another option that I haven’t tried myself is to use the XPather extension.

Using hpricot to find the XPath

If you’re really having problems finding the right XPath of an element, you can also use HPricot to find it. In this example the code prints out the XPath to all table columns containing the text 51,999:

   1  require 'rexml/document'
   2  require 'hpricot'
   3  require 'open-uri'
   4  
   5  url = "http://xyz"
   6  
   7  page = Hpricot(open(url,
   8  	'User-Agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
   9          'Referer'    => 'http://xyz'
  10      	))
  11  
  12  page.search( "//td:contains('51,992')" ).each do |row|
  13    puts row.xpath()
  14  end

The output from the above snippet looks something like this:

   1  /html/body/table[2]/tr[2]/td[3]
   2  /html/body/table[2]/tr[2]/td[3]/table[4]/tr[1]/td[1]
   3  /html/body/table[2]/tr[2]/td[3]/table[4]/tr[1]/td[1]/table[1]/tr[2]/td[2]

Note that sometimes I find that hrpicot is easier to use than Scrubyt, so use what’s best for you.

Miscellaneous problems

The following problem can be solved by following the instructions found here:

   1  Your production scraper has been created: data_extractor_export.rb.
   2  /var/lib/gems/1.8/gems/ParseTreeReloaded-0.0.1/lib/parse_tree_reloaded.rb:129:in `extend': wrong argument type Class (expected Module) (TypeError)
   3         from /var/lib/gems/1.8/gems/ParseTreeReloaded-0.0.1/lib/parse_tree_reloaded.rb:129:in `to_sexp'
   4         from /var/lib/gems/1.8/gems/ParseTreeReloaded-0.0.1/lib/parse_tree_reloaded.rb:93:in `parse_tree_for_method'
   5         from /var/lib/gems/1.8/gems/ruby2ruby-1.1.6/lib/ruby2ruby.rb:1063:in `to_sexp'

Tagged web, scraping, google, scrubyt, ruby, gotcha, hpricot, todelete, obsolete