Description

The PlotDevice Web library offers a collection of services to retrieve content from the internet. You can use the library to query Yahoo! for links, images, news and spelling suggestions, to read RSS and Atom newsfeeds, to retrieve articles from Wikipedia, to collect quality images from morgueFile or Flickr, to get color themes from kuler or Colr, to browse through HTML documents, to clean up HTML, to validate URL’s, to create GIF images from math equations using mimeTeX, to get ironic word definitions from Urban Dictionary.

The PlotDevice Web library works with a caching mechanism that stores things you download from the web, so they can be retrieved faster the next time. Many of the services also work asynchronously. This means you can use the library in an animation that keeps on running while new content is downloaded in the background.

The library bundles Leonard Richardson’s Beautiful Soup to parse HTM, Mark Pilgrim’s Universal Feed Parser for newsfeeds, a connection to John Forkosh’s mathTeX server (thanks Cedric Foellmi), Leif K-Brooks entity replace algorithm, simplejson, and patches for Debian from the people at Indywiki.

Download

download web.zip (390KB)
Last updated for NodeBox 1.9.4.6
Licensed under GPL
Author: Tom De Smedt

Documentation

 


How to get the library up and running

Put the web library folder in the same folder as your script so PlotDevice can find the library.
You can also put it in ~/Library/Application Support/PlotDevice/.

web = ximport("web")

Outside of PlotDevice you can also just do import web.

Proxy servers 

If you are behind a proxy server the library may not be able to connect to the internet.
In that case you need to inform the library with the set_proxy() command:

web.set_proxy("https://www.myproxyserver.com:80", type="https")
                                          

Validating web content

Web content is accessed with a URL, the address you use to connect to a place on the internet. The library has a number of commands to find out what type of content (e.g. web page, image, ...) is associated with a given URL.

The most basic command, is_url() checks whether a given string is a grammatically correct URL (e.g. http://nodebox.net but not htp://nodebox.net). It takes a wait parameter indicating the number of seconds after which the library should stop connecting to the internet and give up.

web.is_url(url, wait=10)

Even if a URL is valid, it might not refer to actual content on the internet. We can check if a URL exists with the not_found() command:

web.url.not_found(url, wait=10)

The following commands are useful to find out what content is associated with the URL. We can discern between HTML web pages which we can parse with page.parse(), newsfeeds which we can parse with newsfeed.parse(), images, audio and video etc. which we can download with url.retrieve().

web.url.is_webpage(url, wait=10)
web.url.is_stylesheet(url, wait=10)
web.url.is_plaintext(url, wait=10)
web.url.is_pdf(url, wait=10)
web.url.is_newsfeed(url, wait=10)
web.url.is_image(url, wait=10)
web.url.is_audio(url, wait=10)
web.url.is_video(url, wait=10)
web.url.is_archive(url, wait=10)
                                                        

Working with URL’s

A URL is  the address you use to connect to a page on the internet, for example: http://nodebox.net. The PlotDevice Web library can do three different things with a URL: download the content associated with it, parse it (find out which parts make up the URL) and construct it from scratch (a simple way to create a URL with HTTP GET or HTTP POST data).

web.download(url, wait=60, cache=None, type=".html")
web.save(url, path="", wait=60)
web.url.retrieve(url, wait=60, asynchronous=False, cache=None, type=".html")
web.url.parse(url)
web.url.create(url="", method="get")

The download() command returns the content associated with the given web address. The command has an optional parameter wait that determines how long to wait for a download. If the time is exceeded, the download is aborted.

The last two parameters can be used to cache downloaded content locally, so it doesn’t have to downloaded again in the future. The cache parameter is a string with the name of a subfolder in /cache where to store content. The type parameter is the file extension of the downloaded content.

The save() command stores the URL’s content at the given local path. If no path is given it will attempt to extract a filename from the URL and store that in the current working directory. The path to the saved file is returned.

The Web library also has easier ways to deal with specific web content like HTML (page.parse() command) or Wikipedia articles (wikipedia.search() command) for example.

The download() command is actually an alias of the url.retrieve() command. This command has an additional asynchronous parameter useful to download stuff in the background while an animation keeps on running. We’ll see about asynchronous downloads later on. The url.retrieve() command returns an object with a data property containing a string with the downloaded content. If you don’t need anything that complicated just use the easy download() command:

# Download an image from the PlotDevice Gallery.
url = "http://nodebox.net/code/data/media/twisted-final.jpg"
img = web.download(url)

# Display the image data in PlotDevice.
image(None, 0, 0, data=img)

# Write the image data to a file.
file = open("twisted.jpg", "w")
file.write(img)
file.close()
        

web_url1

 

The url.parse() command splits a given url into its components. The returned objects has the following properties:

In the same way the url.create() command returns an object with these properties. This command is useful to, for example, construct URL’s with a POST query and pass that to url.retrieve() or page.parse().

For example. this script retrieves the first 10 forum pages from PlotDevice:

url = web.url.create("http://nodebox.net/code/index.php/Share")
url.query["p"] = 1
for i in range(10):
    print web.url.retrieve(url).data
    url.query["p"] += 1
                                                                         

Working with HTML

The PlotDevice Web library uses Leonard Richardson’s Beautiful Soup to parse HTML content. This means you can search and loop through all the tags in the HTML. For example, you might want to download a HTML page from the internet, find all the links in it and then download all those links. Or find all the image tags in the source and then retrieve all those images with download().

The page.parse() command takes a URL as input and returns a Beautiful Soup object. The optional cached parameter determines if downloaded pages should be cached locally for faster retrieval.

web.page.parse(url, wait=10, cached=True)

You can get the meta information in the HTML header with the returned object’s title, description and keywords properties:

html = web.page.parse("http://nodebox.net")

print html.description
>>> PlotDevice is a Mac OS X application that lets you create 2D visuals
>>> (static, animated or interactive) using Python programming code
>>> and export them as a PDF or a QuickTime movie. PlotDevice is free
>>> and well-documented.

print html.keywords
>>>[u'PlotDevice', u'Home']

You can easily get all the links in the HTML with the links() method. It takes an optional external parameter which when True, returns only links to other domains/websites.

html = web.page.parse("http://nodebox.net/code/index.php/About")
print html.links()
>>> [u'http://research.nodebox.net',
>>>  u'http://www.opensource.org/licenses/mit-license.php',
>>>  u'http://www.python.org/', u'http://bert.debruijn.be/kgp/',
>>>  u'http://diveintopython.org/xml_processing/',
>>>  u'http://processing.org',
>>>  u'http://www.freelists.org/archives/the_posthumans/',
>>>  u'http://research.nodebox.net'
>>> ]

The find_all() method returns a list of specific tags. The find() method just returns the first tag:

html = web.page.parse("http://nodebox.net/")

print html.find("title").string
>>> PlotDevice | Home

titles = html.find_all("h2")
for title in titles:
    print title.string
>>> News
>>> Current projects
>>> Gallery favorites

content = html.find(id="content")
print web.html.plain(content)
>>> Welcome to PlotDevice PlotDevice is a Mac OS X application
>>> that lets you create 2D visuals (static, animated or interactive)
>>> using Python programming code and export them as a PDF or
>>> a QuickTime movie. PlotDevice is free and well-documented.
>>> Read more
>>>
>>> Download PlotDevice for Mac OS X (version 1.8.5) Universal Binary
>>>
>>> Latest updates:
>>>
>>> * Interactivity
>>> * Stop running scripts by hitting command-dot.
>>> ...

As you can see you can supply tag names or attribute-value pairs to the find methods.

The find() and find_all() methods return Tag objects that each have find() and find_all() too. Alternatively, you can also find tags more directly, for example: html.body.p returns a list of all p tags.

html = web.page.parse("http://nodebox.net/")

list = html.find(id="content").find("ul")
print web.html.plain(list)
>>> * Interactivity
>>> * Stop running scripts by hitting command-dot.
>>> * Transparent PDFs with the background() command.
>>> * Fast, integrated path mathematics .
>>> * Store libaries centrally in the Application Support folder.

# These statements retrieve exactly the same.
list = html.body(id="content")[0].ul
list = html.body.ul

If you need to retrieve tags by their CSS classname, use the find_class() method.

To get attributes from a tag, address it as a dictionary:

html = web.page.parse("http://nodebox.net/")
html.body.a["href"] # the first link's href attribute
>>> Home
                                                                 

The PlotDevice Web library has various commands to clean up HTML.

# Replaces HTML special characters by readable characters.
web.html.replace_entities(unicode, placeholder=" ")
# Removes all tags from HTML except those in the exclude list.
web.html.strip_tags(html, exclude=[], linebreaks=False,
                    blocks="\n", breaks="\n", columns="\n")
web.html.strip_javascript(html)
web.html.strip_inline_css(html)
web.html.strip_comments(html)
web.html.strip_forms(html)
# If there are 10 consecutive spaces, 9 of them are removed.
web.html.collapse_spaces(str)
# Allow only a maximum of max linebreaks to build up.
web.html.collapse_linebreaks(str, max=2)
# Converts tabs to spaces, optionally leaving the left indentation unmodified.
web.html.collapse_tabs(str, indent=False)
# Combines all of the above.
web.html.plain(html)
                                                                                                                            

Querying Yahoo! for links, images and news

Before you can use the Web library to query the Yahoo! search engine, you need to obtain a license key: http://developer.yahoo.com/search/

Click  ‘get an application ID’. Fill out the form and you’ll end up with a long string of numbers and characters which is your Yahoo! license key. It entitles you to 5000 queries a day. Now register your license key in your PlotDevice script:

web.yahoo.license_key("myID")
print web.yahoo.license_key()
>>> myID

Note that you can query Yahoo! without setting a license key, in which case you are using a default key that you share with all the other PlotDevice users who work with the Web library.

Use the yahoo.search(), yahoo.search_images() and yahoo.search_news() commands to query Yahoo! for links to relevant webpages/images/news:

web.yahoo.search(q, start=1, count=10, context=None, cached=False)
web.yahoo.search_images(q, start=1, count=10, cached=False)
web.yahoo.search_news(q, start=1, count=10, cached=False)

The commands take a q query parameter, and optional start, count and cached parameters. The start parameter defines the first link to return, count defines the total amount of links to return. The cached parameter defines if Yahoo queries are cached locally (so they can be retrieved faster in the future).

results = web.yahoo.search("plotdevice", start=1, count=5, cached=False)
for item in results:
    print item.title
>>> PlotDevice | Home
>>> PlotDevice | Features
>>> visualcomplexity.com | PlotDevice
>>> PlotDevice - Wikipedia, the free encyclopedia
>>> Nodebox - SWiK

Each item in the list of results is a YahooResult object with the following properties:

The list of results has a total property containing the total number of results Yahoo! has for your query:

print results.total
>>> 37200
                                                                                                                      

Improving Yahoo! results with a contextual search

Suppose you are querying Yahoo! for apple. Most likely Yahoo! will return links to pages relating to the Apple Computer company. But perhaps you wanted links to apples as in fruit. The yahoo.search() command has an optional context parameter which you can supply a description of what you mean exactly with apple:

ctx = '''
The apple tree was perhaps the earliest tree to be cultivated,
and apples have remained an important food in all cooler climates.
To a greater degree than other tree fruit, except possibly citrus,
apples store for months while still retaining their nutritive value.
We are not looking for a company named Apple.
'''
results = web.yahoo.search("apple", count=5, context=ctx)
print r.total
for item in results:
    print item.title
>>> Apple - Wikipedia, the free encyclopedia
>>> Apple Core
>>> Apple - Free Encyclopedia
>>> Apple : Apple (fruit)
>>> About the Apple -- Fruit

 


Using Yahoo! to suggest spelling corrections

To get spelling suggestions from Yahoo, use the yahoo.suggest_spelling() command. It returns a list of suggested spelling corrections:

corrections = web.yahoo.suggest_spelling ("amazoon", cached=False)
print corrections
>>> ['amazon']
     

               


Using Yahoo! to sort associatively

You can use Yahoo! to sort concepts according to association. Is sky more green, red or blue?

colors = ["green", "blue", "red"]
sorted = web.yahoo.sort(colors, "sky", strict=False, cached=True)
for word, weight in sorted:
    print word, weight
>>> blue sky 0.396039408425
>>> red sky 0.33604773392
>>> green sky 0.267912857655

In this example, Yahoo! is queried for green sky, blue sky and red sky. The result is a sorted list of (query, weight) tuples. We learn that blue is the color best associated with sky.

The Prism algorithm roughly works in this way.

 


Querying Google

You can run Google queries in the same way as querying Yahoo!.
The library has the following commands available:

web.google.search(q, start=0, cached=False)
web.google.search_images(q, start=0, size="", cached=False)
web.google.search_news(q, start=0, cached=False)
web.google.search_blogs(q, start=0, cached