Skip to content

Instantly share code, notes, and snippets.

@madjar
Created September 23, 2013 13:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madjar/6670581 to your computer and use it in GitHub Desktop.
Save madjar/6670581 to your computer and use it in GitHub Desktop.
An attempt to find the perfect scrapper form
import re
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
Torrent = namedtuple('Torrent', 'name link magnet torrent created size'
' user seeders leechers')
def torrent(soup):
t = {}
cats, links, seeders, leechers = soup.findAll('td')
all_links = links.findAll('a')
t['name'] = all_links[0].get_text()
t['link'] = all_links[0]['href']
t['magnet'] = all_links[1]['href']
try:
t['torrent'] = all_links[2]['href']
except IndexError:
t['torrent'] = None
t['created'], t['size'], t['user'] = re.search('Uploaded (.*), Size (.*), ULed by (.*)',
links.find('font').get_text()).groups(0)
t['seeders'] = int(seeders.get_text())
t['leechers'] = int(seeders.get_text())
return Torrent(**t)
Page = namedtuple('Page', 'torrents')
def page(soup):
return Page(torrents=list(map(torrent, soup.find(['table']).findAll('tr')[1:-1])))
def search(query):
url = 'http://thepiratebay.sx/search/{}'.format(query)
s = BeautifulSoup(requests.get(url).text)
p = page(s)
return p.torrents
if __name__ == '__main__':
for t in search('mad men'):
print(t.name)
@madjar
Copy link
Author

madjar commented Sep 23, 2013

I wanted an explicit list of attributres, but if I drop that, I might as well put everything in a class's __init__.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment