Thursday, April 22, 2010

Using YQL create Food Network Search

More YQL, gotta love how easy they have made this!!

I have found that Food Network can be quite good at making boring foods, well... not so boring. Wondered what it would take to search their system from another webpage. They don't have a feed for you, so what to do? YQL's html table...

Go to the YQL Console, and enter:

select h3 from html where url="http://www.foodnetwork.com/search/delegate.do?fnSearchString=FOODITEM&fnSearchType=site" and
xpath='//div[@class="result-item"]'

as your query. You'll notice it breaks it down to a simple array of h3 elements.
From there, simply create an array and show the results in an unordered list.

HTML Page:


  1. Add jQuery to your Page

  2. Create a textbox called txtSearch

  3. Create a button called btnSearch

  4. Create an unordered list called searchResults



JS Code:

function searchRecipes(search) {
$('#searchResults').empty();
$.getJSON(
"http://query.yahooapis.com/v1/public/yql?q=select%20h3%20from%20html(5)%20where%20url%3D%22http%3A%2F%2Fwww.foodnetwork.com%2Fsearch%2Fdelegate.do%3FfnSearchString%3D" + search + "%26fnSearchType%3Dsite%22%20and%0D%0A%20%20%20%20%20%20xpath%3D'%2F%2Fdiv%5B%40class%3D%22result-item%22%5D'&format=json&callback=?",
function (data) {
$.each(data.query.results,
function (index, item) {
for (i = 0; i < item.length; i++) {
var each = item[i];
var link = (each.h3.a.href).replace('/', 'http://www.foodnetwork.com/');
$('<li></li>').html('' + each.h3.a.content + '').appendTo('#searchResults');
}
});
});
}

$("#btnSearch").click(function () {
var searchText = document.getElementById('txtSearch').value;
if (searchText == "") {
alert('You must first enter a food to search!');
}
else {
searchRecipes(searchText);
}
});

There you have it. Enter a food to search in the textbox, click on btnSearch, and a list of recipes are found. Only returns 12, as that is how the site is setup, but its a nice basic example of yql page scraping...

Oh, by the way, if you want a copy of the script, feel free to download at:

http://www.joshuablackstone.com/Scripts/Searches/FoodNetwork.js

0 comments: