Created
September 23, 2013 13:42
-
-
Save madjar/6670581 to your computer and use it in GitHub Desktop.
An attempt to find the perfect scrapper form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wanted an explicit list of attributres, but if I drop that, I might as well put everything in a class's
__init__
.