How to automatically search and download torrents with Python and Scrapy

 

The Goal

To automatically perform keyword based searches at one of  kickasstorrents categories, scrap relevant data that match our keywords and category, download the .torrent file and push it to transmission torrent client for auto downloading .
Setup a cron job to repeat the search at intervals, scraping and downloading torrents automatically.

Check out the code directly from Github.

 

Example Test Cases

Search and download newly posted python books every morning at 09:00:
  1. 0 */9 * * * cd ~/development/scrapy/kickass &&  /usr/local/bin/scrapy crawl kickass -a category=books -a keywords='python' >> ~/scrapy.log 2>&1  
Search and automatically download latest X Men comics posted at kickasstorrents under comics category, every fifty (50) minutes. Setup the following cron job:
  1. */50 * * * * cd ~/development/scrapy/kickass &&  /usr/local/bin/scrapy crawl kickass -a category=comics -a keywords='x-men,xmen,x men' >> ~/scrapy.log 2>&1  

 

 

What we need

Three classes and the Scrapy framework: 
TorrentItem class to store torrent information
KickassSpider classto scrap torrent data
Pipilene class to follow URL redirects invoking curl and download torrent files

But first, let's install python, python dev libraries, libxml2 and Scrapy.
 
  • sudo apt-get install python - Python 2.6 or 2.7
  • Prerequisities for Scrapy
  • sudo apt-get install python-dev - python dev libraries
  • sudo apt-get install libxml2
  • pip install Scrapy or easy_install Scrapy - Scrapy framework

 

 

Create a new Scrapy project

After installing scrapy, create a new project from the command line:
  1. $ scrapy startproject kickass  
This will create all necessary directories and provide initial structure for our project with default settings and some basic template classes.
 

 

Torrent Item

We need a class to store torrent data such as title, url, size etc.
Edit the existing items.py file in directory kickass/kickass:
  1. from scrapy.item import Item, Field   
  2.   
  3. class TorrentItem(Item):   
  4.  title = Field()    
  5.  url = Field()   
  6.  size = Field()   
  7.  sizeType = Field()   
  8.  age = Field()   
  9.  seed = Field()   
  10.  leech = Field()   
  11.  torrent = Field()   
  12. pass  
 

Kickass Spider

Next we define the Spider, responsible for scraping data and storing TorrentItem information.
We instantiate it with two arguments, category and keywords. Create a new file kickass_spider.py in directory kickass/kickass/spiders:
  1. from scrapy.spider import BaseSpider   
  2. from scrapy.selector import HtmlXPathSelector   
  3. from scrapy.http import Request   
  4. from scrapy.utils.response import get_base_url   
  5.   
  6. from kickass.items import TorrentItem   
  7.   
  8. class KickassSpider(BaseSpider):   
  9.   
  10.  name = "kickass"  
  11.   
  12.  allowed_domains = [   
  13.   "kat.ph"  
  14.  ]   
  15.   
  16.  def __init__(self, *args, **kwargs):    
  17.   super(KickassSpider, self).__init__(*args, **kwargs)   
  18.   self.keywords = kwargs['keywords'].split(',')   
  19.   self.category = kwargs['category']   
  20.   self.start_urls = [   
  21.    'http://kat.ph/usearch/category%3A'    
  22.    + self.category    
  23.    + '/?field=time_add&sorder=desc'  
  24.   ]   
  25.   
  26.  def parse(self, response):   
  27.   hxs = HtmlXPathSelector(response)   
  28.   entries = hxs.select('//tr[starts-with(@id,"torrent_category")]')   
  29.   items = []   
  30.   for entry in entries:   
  31.    item = TorrentItem()   
  32.    item['title'] = entry.select('td[1]/div[2]/a[2]/text()').extract()   
  33.    item['url'] = entry.select('td[1]/div[2]/a[2]/@href').extract()   
  34.    item['torrent'] = entry.select('td[1]/div[1]/a[starts-with(@title,"Download torrent file")]/@href').extract()   
  35.    item['size'] = entry.select('td[2]/text()[1]').extract()   
  36.    item['sizeType'] = entry.select('td[2]/span/text()').extract()   
  37.    item['age'] = entry.select('td[4]/text()').extract()   
  38.    item['seed'] = entry.select('td[5]/text()').extract()   
  39.    item['leech'] = entry.select('td[6]/text()').extract()      
  40.    for s in self.keywords:   
  41.     if s.lower() in item['title'][0].lower():   
  42.      items.append(item)   
  43.      break  
  44.   return items   
  45.     
The spider, simply parses the first page of torrents for a given category sorted by age - most recent first.
Then extracts torrent information and if a keyword matches a torrent title is added to a list of TorrentItems to be later processed by the pipeline defined in the next step.
The URL for a given category sorted buy time looks like this:
http://kat.ph/usearch/category%3Abooks/?field=time_add&sorder=desc

 

Torrent Pipeline

All TorrentItems that were scrapped by the spider by matching the keyword list are passed to this pipeline for further processing. In our case, the pipeline will be responsible for downloading the actual torrent files and invoking transmission torrent client. Edit the file pipelines.py in directory kickass/kickass:
 
  1. import json   
  2. import subprocess   
  3. import time   
  4. import urllib2   
  5.   
  6. from scrapy.http.request import Request   
  7.   
  8. class TorrentPipeline(object):   
  9.   
  10.  def process_item(self, item, spider):     
  11.    print 'Downloading ' + item['title'][0]   
  12.    path = 'http:'+item['torrent'][0]        
  13.    subprocess.call(['./curl_torrent.sh',path])   
  14.    time.sleep(10# pause to prevent 502 eror   
  15.    return item  
Next, we must declare the new pipeline in kickass/kickass/settings.py configuration file. Add the following entry:
ITEM_PIPELINES = ['kickass.pipelines.TorrentPipeline']
 

CURLing for the Torrent

The pipeline gets the URL path from the scrapped TorrentItem and calls script curl_torrent.sh.
The script follows the URL and the redirection to get the real filename of the torrent and donwloads it. Then, it runs transmission to start the download.
Place the script under your kickass/ directory.
  1. #!/bin/bash   
  2. # Downloads .torrent files from kickass.com links   
  3. # following redirects and getting the actual torrent   
  4. # filename   
  5.   
  6. AGENT="'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/20070802 SeaMonkey/1.1.4)'"  
  7.   
  8. function usage(){  
  9.  echo "Usage: 

     

    How to automatically search and download torrents with Python and Scrapy

     

    The Goal

    To automatically perform keyword based searches at one of  kickasstorrents categories, scrap relevant data that match our keywords and category, download the .torrent file and push it to transmission torrent client for auto downloading .
    Setup a cron job to repeat the search at intervals, scraping and downloading torrents automatically.

    Check out the code directly from Github.

     

    Example Test Cases

    Search and download newly posted python books every morning at 09:00:
    1. 0 */9 * * * cd ~/development/scrapy/kickass &&  /usr/local/bin/scrapy crawl kickass -a category=books -a keywords='python' >> ~/scrapy.log 2>&1  
    Search and automatically download latest X Men comics posted at kickasstorrents under comics category, every fifty (50) minutes. Setup the following cron job:
    1. */50 * * * * cd ~/development/scrapy/kickass &&  /usr/local/bin/scrapy crawl kickass -a category=comics -a keywords='x-men,xmen,x men' >> ~/scrapy.log 2>&1  

     

     

    What we need

    Three classes and the Scrapy framework: 
    TorrentItem class to store torrent information
    KickassSpider classto scrap torrent data
    Pipilene class to follow URL redirects invoking curl and download torrent files

    But first, let's install python, python dev libraries, libxml2 and Scrapy.
     
    • sudo apt-get install python - Python 2.6 or 2.7
    • Prerequisities for Scrapy
    • sudo apt-get install python-dev - python dev libraries
    • sudo apt-get install libxml2
    • pip install Scrapy or easy_install Scrapy - Scrapy framework

     

     

    Create a new Scrapy project

    After installing scrapy, create a new project from the command line:
    1. $ scrapy startproject kickass  
    This will create all necessary directories and provide initial structure for our project with default settings and some basic template classes.
     

     

    Torrent Item

    We need a class to store torrent data such as title, url, size etc.
    Edit the existing items.py file in directory kickass/kickass:
    1. from scrapy.item import Item, Field   
    2.   
    3. class TorrentItem(Item):   
    4.  title = Field()    
    5.  url = Field()   
    6.  size = Field()   
    7.  sizeType = Field()   
    8.  age = Field()   
    9.  seed = Field()   
    10.  leech = Field()   
    11.  torrent = Field()   
    12. pass  
     

    Kickass Spider

    Next we define the Spider, responsible for scraping data and storing TorrentItem information.
    We instantiate it with two arguments, category and keywords. Create a new file kickass_spider.py in directory kickass/kickass/spiders:
    1. from scrapy.spider import BaseSpider   
    2. from scrapy.selector import HtmlXPathSelector   
    3. from scrapy.http import Request   
    4. from scrapy.utils.response import get_base_url   
    5.   
    6. from kickass.items import TorrentItem   
    7.   
    8. class KickassSpider(BaseSpider):   
    9.   
    10.  name = "kickass"  
    11.   
    12.  allowed_domains = [   
    13.   "kat.ph"  
    14.  ]   
    15.   
    16.  def __init__(self, *args, **kwargs):    
    17.   super(KickassSpider, self).__init__(*args, **kwargs)   
    18.   self.keywords = kwargs['keywords'].split(',')   
    19.   self.category = kwargs['category']   
    20.   self.start_urls = [   
    21.    'http://kat.ph/usearch/category%3A'    
    22.    + self.category    
    23.    + '/?field=time_add&sorder=desc'  
    24.   ]   
    25.   
    26.  def parse(self, response):   
    27.   hxs = HtmlXPathSelector(response)   
    28.   entries = hxs.select('//tr[starts-with(@id,"torrent_category")]')   
    29.   items = []   
    30.   for entry in entries:   
    31.    item = TorrentItem()   
    32.    item['title'] = entry.select('td[1]/div[2]/a[2]/text()').extract()   
    33.    item['url'] = entry.select('td[1]/div[2]/a[2]/@href').extract()   
    34.    item['torrent'] = entry.select('td[1]/div[1]/a[starts-with(@title,"Download torrent file")]/@href').extract()   
    35.    item['size'] = entry.select('td[2]/text()[1]').extract()   
    36.    item['sizeType'] = entry.select('td[2]/span/text()').extract()   
    37.    item['age'] = entry.select('td[4]/text()').extract()   
    38.    item['seed'] = entry.select('td[5]/text()').extract()   
    39.    item['leech'] = entry.select('td[6]/text()').extract()      
    40.    for s in self.keywords:   
    41.     if s.lower() in item['title'][0].lower():   
    42.      items.append(item)   
    43.      break  
    44.   return items   
    45.     
    The spider, simply parses the first page of torrents for a given category sorted by age - most recent first.
    Then extracts torrent information and if a keyword matches a torrent title is added to a list of TorrentItems to be later processed by the pipeline defined in the next step.
    The URL for a given category sorted buy time looks like this:
    http://kat.ph/usearch/category%3Abooks/?field=time_add&sorder=desc

     

    Torrent Pipeline

    All TorrentItems that were scrapped by the spider by matching the keyword list are passed to this pipeline for further processing. In our case, the pipeline will be responsible for downloading the actual torrent files and invoking transmission torrent client. Edit the file pipelines.py in directory kickass/kickass:
     
    1. import json   
    2. import subprocess   
    3. import time   
    4. import urllib2   
    5.   
    6. from scrapy.http.request import Request   
    7.   
    8. class TorrentPipeline(object):   
    9.   
    10.  def process_item(self, item, spider):     
    11.    print 'Downloading ' + item['title'][0]   
    12.    path = 'http:'+item['torrent'][0]        
    13.    subprocess.call(['./curl_torrent.sh',path])   
    14.    time.sleep(10# pause to prevent 502 eror   
    15.    return item  
    Next, we must declare the new pipeline in kickass/kickass/settings.py configuration file. Add the following entry:
    ITEM_PIPELINES = ['kickass.pipelines.TorrentPipeline']
     

    CURLing for the Torrent

    The pipeline gets the URL path from the scrapped TorrentItem and calls script curl_torrent.sh.
    The script follows the URL and the redirection to get the real filename of the torrent and donwloads it. Then, it runs transmission to start the download.
    Place the script under your kickass/ directory.
    1. #!/bin/bash   
    2. # Downloads .torrent files from kickass.com links   
    3. # following redirects and getting the actual torrent   
    4. # filename   
    5.   
    6. AGENT="'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/20070802 SeaMonkey/1.1.4)'"  
    7.   
    8. function usage(){  
    9.  echo "Usage: $0 [Kickass Torrent URL]"  
    10.   exit 1   
    11. }  
    12.   
    13. if [ ! -n "$1" ]  
    14. then  
    15.     usage   
    16. fi  
    17.   
    18. name=`echo $1 | sed 's/.*kat.ph.//'`".torrent"  
    19. curl --globoff --compressed -A '$AGENT' -L --post302 $1 > $name  
    20. transmission -m $name  
     

    Schedule the Spider

    To start the spider we run scrapy with the crawl command and the name of the spider, in our case kickass.
    However, we need to supply two arguments. One for category, and a list of keywords.
     
    For example: 
    scrapy crawl kickass -a category=books -a keywords='python,java,scala topics'
     
    To have the spider run every 10 minutes we can schedule a cron job
    .
    From the command line type crontab -e and add the following  line:
     
    */10 * * * * cd ~/development/scrapy/kickass &&  /usr/local/bin/scrapy crawl kickass -a category=books -a keywords='python,java,scala topics' >> ~/scrapy.log 2>&1
     
     

    Considerations

    Finally, is recommended to modify the setting.py file under kickass/kickass directory to tune the spiders behavior and adjust logging. The following settings introduce a download delay of 5 seconds per request and limit concurrent requests to 1. That is to prevent hammering. Here is the complete file:
    # Scrapy settings for kickass project
    
    BOT_NAME = 'kickass'
    
    SPIDER_MODULES = ['kickass.spiders']
    NEWSPIDER_MODULE = 'kickass.spiders'
    ITEM_PIPELINES = ['kickass.pipelines.TorrentPipeline',]
    
    # Download and traffic settings.
    # Limit concurrent requests and add a 
    # download delay to minimize hammering.
    USER_AGENT = 'http://www.kickasstorrents.com)'
    DOWNLOAD_DELAY = 5
    RANDOMIZE_DOWNLOAD_DELAY = False
    CONCURRENT_REQUESTS_PER_DOMAIN = 1 #  Default: 8
    #SCHEDULER = 'scrapy.core.scheduler.Scheduler'
    
    # Log Settings
    LOG_ENABLED = True
    LOG_LEVEL = 'INFO' # Levels: CRITICAL, ERROR, WARNING, INFO, DEBUG
    LOG_FILE = './kickass.log'
    
    
     

    This is my first attempt at doing anything with python so i guess some things could be done more efficiently. I am still experimenting with the language, and coming from a heavy Java background i can confess that i am fascinated. Also, i am pretty sure that spawning a new process with curl to fetch the torrent is not the most optimal way to do it.

    Feel free to directly checkout the code at Github, and point out improvement / corrections.
    I would very much appreciate that.

     

    [출처] http://fuzz-box.blogspot.kr/2013/03/how-to-automatically-search-download-torrent-python-scrapy.html

     

     

 [Kickass Torrent URL]"  
  •   exit 1   
  • }  
  •   
  • if [ ! -n "40832" ]  
  • then  
  •     usage   
  • fi  
  •   
  • name=`echo 40832 | sed 's/.*kat.ph.//'`".torrent"  
  • curl --globoff --compressed -A '$AGENT' -L --post302 40832 > $name  
  • transmission -m $name  
  • [Kickass Torrent URL]" exit 1 } if [ ! -n "40832" ] then usage fi name=`echo 40832 | sed 's/.*kat.ph.//'`".torrent" curl --globoff --compressed -A '$AGENT' -L --post302 40832 > $name transmission -m $name
     

    Schedule the Spider

    To start the spider we run scrapy with the crawl command and the name of the spider, in our case kickass.
    However, we need to supply two arguments. One for category, and a list of keywords.
     
    For example: 
    scrapy crawl kickass -a category=books -a keywords='python,java,scala topics'
     
    To have the spider run every 10 minutes we can schedule a cron job
    .
    From the command line type crontab -e and add the following  line:
     
    */10 * * * * cd ~/development/scrapy/kickass &&  /usr/local/bin/scrapy crawl kickass -a category=books -a keywords='python,java,scala topics' >> ~/scrapy.log 2>&1
     
     

    Considerations

    Finally, is recommended to modify the setting.py file under kickass/kickass directory to tune the spiders behavior and adjust logging. The following settings introduce a download delay of 5 seconds per request and limit concurrent requests to 1. That is to prevent hammering. Here is the complete file:
    # Scrapy settings for kickass project
    
    BOT_NAME = 'kickass'
    
    SPIDER_MODULES = ['kickass.spiders']
    NEWSPIDER_MODULE = 'kickass.spiders'
    ITEM_PIPELINES = ['kickass.pipelines.TorrentPipeline',]
    
    # Download and traffic settings.
    # Limit concurrent requests and add a 
    # download delay to minimize hammering.
    USER_AGENT = 'http://www.kickasstorrents.com)'
    DOWNLOAD_DELAY = 5
    RANDOMIZE_DOWNLOAD_DELAY = False
    CONCURRENT_REQUESTS_PER_DOMAIN = 1 #  Default: 8
    #SCHEDULER = 'scrapy.core.scheduler.Scheduler'
    
    # Log Settings
    LOG_ENABLED = True
    LOG_LEVEL = 'INFO' # Levels: CRITICAL, ERROR, WARNING, INFO, DEBUG
    LOG_FILE = './kickass.log'
    
    
     

    This is my first attempt at doing anything with python so i guess some things could be done more efficiently. I am still experimenting with the language, and coming from a heavy Java background i can confess that i am fascinated. Also, i am pretty sure that spawning a new process with curl to fetch the torrent is not the most optimal way to do it.

    Feel free to directly checkout the code at Github, and point out improvement / corrections.
    I would very much appreciate that.

     

    경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
    어린이용이며, 설치가 필요없는 브라우저 게임입니다.
    https://s1004games.com

    [출처] http://fuzz-box.blogspot.kr/2013/03/how-to-automatically-search-download-torrent-python-scrapy.html

     

     

    본 웹사이트는 광고를 포함하고 있습니다.
    광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
    번호 제목 글쓴이 날짜 조회 수
    » How to automatically search and download torrents with Python and Scrapy 졸리운_곰 2017.02.26 774
    136 Web scraping, article extraction and sentiment analysis with Scrapy, Goose and TextBlob 졸리운_곰 2017.02.26 395
    135 Windows 64 bit 에서 Python 단일 EXE 파일 만들기 file 졸리운_곰 2017.02.26 975
    134 [Python] 네이버 주식 종목별 일별 데이터 가져오기 file 졸리운_곰 2017.02.24 1869
    133 [파이썬으로 웹 크롤러 만들기] 크롤링 시작하기(3/3) file 졸리운_곰 2017.02.16 705
    132 [파이썬으로 웹 크롤러 만들기] 크롤링 시작하기(2/3) file 졸리운_곰 2017.02.16 709
    131 [파이썬으로 웹 크롤러 만들기] 크롤링 시작하기(1/3) file 졸리운_곰 2017.02.16 772
    130 Python의 Generator와 yield 키워드 졸리운_곰 2017.02.16 415
    129 Python으로 RESTAPI 이용하기 졸리운_곰 2017.02.11 462
    128 Learning Django and AngularJS 졸리운_곰 2017.02.06 1694
    127 Application Skeleton for Flask and AngularJS file 졸리운_곰 2017.02.06 596
    126 Flask by Example - Integrating Flask and Angular file 졸리운_곰 2017.02.06 1002
    125 KAIST의 Flask 세미나 자료 whitegold-20130515-1.pdf file 졸리운_곰 2017.02.01 850
    124 Flask로 만들어 보는 WSGI 어플리케이션 file 졸리운_곰 2017.02.01 529
    123 [Flask, python], 빠르게 시작하기 file 졸리운_곰 2017.01.29 1493
    122 [Django 17] Django 디버깅 file 졸리운_곰 2017.01.28 1185
    121 [Django 16] Django - Site Deployment 졸리운_곰 2017.01.28 598
    120 [Django 15] 샘플 - Feedback 예제 file 졸리운_곰 2017.01.28 474
    119 [Django 14] Static 파일 file 졸리운_곰 2017.01.28 794
    118 [Django 13] Django 폼 (Form) 졸리운_곰 2017.01.28 347
    대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
    통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
    대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED