Parsing HTML with Python

Came across an interesting scenario this week where I decided to try and use Python for parsing HTML. Turns out to quite straight forward and something I could imagine using more often in the future.

We were trying to grab the a dynamic link from this page at twitch

The link we were after was the most viewed channel at any particular time:

The most viewed channel is always in this location/element

First attempt was to load up that page in an <iframe> allowing our own JavaScript to grab the relevant URL then forward. however forces forwarding when iframes are detected, presumably for proprietary reasons. So javascript was not really an option.

After experimenting with Python’s lxml it was really straight forward and effective. It is apparently quite efficient using C core ( too. The module I used is documented quite well here: With a little bit of trial an error a brief python script successfully grabs the relevant information.

Then using PHP’s popen() method I can simply call the python script and use the return value as a php variable for a header redirect.

Links to source: – Python script

get_link.php – PHP calling python and using return value :


$handle = popen('python -i ./ 2>&1', 'r');
$read = fread($handle, 2096);
header('Location: '.$read);


Python source:

import urllib
from lxml import html

def getElement():
        f = urllib.urlopen("")
        # Read from the object, storing the page's contents in 's'.
        s =
        f.close()# Read from the object, storing the page's contents in 's'.
        doc = html.document_fromstring(s)
        doc = doc.get_element_by_id('directory_channels')
        #rVal = trimDoc.text_content()
        doc = doc.find_class('thumb')
        rVal = html.tostring(doc[0]).split()[2]
        return makeUrl(rVal)

def makeUrl(thumbString):
        return "" +  thumbString[6:-2]

if __name__ == "__main__":
        print getElement()


Leave a Reply

Your email address will not be published. Required fields are marked *