#!/usr/bin/env python
import webbrowser
import urllib
import urllib2
import re
from HTMLParser import HTMLParser
import argparse


# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    title = ''
    q = ''
    state = 'looking'
    results = []

    def __init__(self, q):
        HTMLParser.__init__(self)
        self.q = q.lower()

    def handle_starttag(self, tag, attrs):
        if tag == 'title':
            self.state = 'title'
        if tag == 'magnet' and self.state == 'matched':
            self.state = 'magnet'

    def handle_data(self, data):
        if self.state == 'title':
            if data.lower().find(self.q) != -1:
                self.title = data
                self.state = 'matched'
            else:
                self.state = 'looking'
        if self.state == 'magnet':
            self.results.append(['magnet:?xt=urn:btih:' + urllib.quote(data) + '&dn=' + urllib.quote(self.title), '?', '?'])
            self.state = 'looking'


def main():
    parser = argparse.ArgumentParser(description='Finds and downloads torrents from the Pirate Bay')
    parser.add_argument('q', metavar='search_term', help="The term to search for")
    parser.add_argument('--local', dest='database', help="An xml file containing the Pirate Bay database")

    def local(args):
        xml_str = ''
        with open(args.database, 'r') as f:
            xml_str += f.read()
        htmlparser = MyHTMLParser(args.q)
        htmlparser.feed(xml_str)
        return htmlparser.results

    #todo: redo this with html parser instead of regex
    def remote(args):
        f = urllib2.urlopen('http://thepiratebay.se/search/' + args.q.replace(" ", "+") + '/0/7/0')
	res = f.read()
        found = re.findall(""""(magnet\:\?xt=[^"]*)|<td align="right">([^<]+)</td>""", res)
        state = "seeds"
        curr = ['',0,0] #magnet, seeds, leeches
        res_l = []
        for f in found:
            if f[1] == '':
                curr[0] = f[0]
            else:
                if state == 'seeds':
                    curr[1] = f[1]
                    state = 'leeches'
                else:
                    curr[2] = f[1]
                    state = 'seeds'
                    res_l.append(curr)
                    curr = ['', 0, 0]
        return res_l

    args = parser.parse_args()
    if args.database:
        mags = local(args)
    else:
        mags = remote(args)

    print "S=seeders"
    print "L=leechers"
    if mags:
        for m in range(len(mags)):
            magnet = mags[m]
            name = re.search("dn=([^\&]*)", magnet[0])
            print str(m) + '. S:' + str(magnet[1]) + ' L:' + str(magnet[2]) + ' ', urllib.unquote(name.group(1).encode('ascii')).decode('utf-8').replace("+", " ")
        l = raw_input("Select a link: ")
        try:
            choice = int(l)
        except Exception:
            choice = None
        if not choice == None:
            webbrowser.open(mags[choice][0])
        else:
            print "Cancelled."
    else:
        print "no results"

if __name__ == "__main__":
    main()

@@ -1302,16 +1302,136 @@
 tabase%22)
+%0A    parser.add_argument('-p', dest='pages', help=%22The number of pages to fetch (doesn't work with --local)%22, default=1)
 %0A%0A    de
@@ -1721,32 +1721,334 @@
 f remote(args):%0A
+        res_l = %5B%5D%0A        try:%0A            pages = int(args.pages)%0A            if pages %3C 1:%0A                raise Exception('')%0A        except Exception:%0A            raise Exception(%22Please provide an integer greater than 0 for the number of pages to fetch.%22)%0A%0A        for page in xrange(pages):%0A    
         f = urll
@@ -2127,17 +2127,44 @@
 + '/
-0/7/0')%0A%09
+' + str(page) + '/7/0')%0A            
 res 
@@ -2166,32 +2166,36 @@
  res = f.read()%0A
+    
         found = 
@@ -2270,32 +2270,36 @@
 %22, res)%0A        
+    
 state = %22seeds%22%0A
@@ -2298,32 +2298,36 @@
 %22seeds%22%0A        
+ 
+   
 curr = %5B'',0,0%5D 
@@ -2350,39 +2350,24 @@
 leeches%0A    
-    res_l = %5B%5D%0A
         for 
@@ -2390,16 +2390,20 @@
         
+    
 if f%5B1%5D 
@@ -2421,24 +2421,28 @@
             
+   
+ 
 curr%5B0%5D = f%5B
@@ -2448,32 +2448,36 @@
 %5B0%5D%0A            
+    
 else:%0A          
@@ -2478,24 +2478,28 @@
             
+ 
+   
 if state == 
@@ -2523,24 +2523,28 @@
             
+   
+ 
 curr%5B1%5D = f%5B
@@ -2538,32 +2538,36 @@
  curr%5B1%5D = f%5B1%5D%0A
+    
                 
@@ -2596,38 +2596,46 @@
                 
+    
 else:%0A
+    
                 
@@ -2665,32 +2665,36 @@
                 
+    
 state = 'seeds'%0A
@@ -2693,16 +2693,20 @@
 'seeds'%0A
+    
         
@@ -2736,16 +2736,20 @@
 d(curr)%0A
+    
         
@@ -2919,16 +2919,51 @@
 (args)%0A%0A
+    if mags and len(mags) %3E 0:%0A    
     prin
@@ -2972,24 +2972,28 @@
 %22S=seeders%22%0A
+    
     print %22L
@@ -3007,21 +3007,8 @@
 rs%22%0A
-    if mags:%0A
     

add variable number of pages to fetch option