python torrent 자동 다운로드 :

How to automatically search and download torrents with Python and Scrapy

 

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: 

    python torrent 자동 다운로드 :

    How to automatically search and download torrents with Python and Scrapy

     

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

     
    본 웹사이트는 광고를 포함하고 있습니다.
    광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
    번호 제목 글쓴이 날짜 조회 수
    97 텐서플로우 시작하기 file 졸리운_곰 2016.11.25 773
    96 Flask by Example - Integrating Flask and Angular file 졸리운_곰 2016.11.20 702
    95 Integrating Python and R Part III: An Extended Example file 졸리운_곰 2016.11.16 527
    94 Integrating Python and R Part II – Executing R from Python and Vice Versa 졸리운_곰 2016.11.16 1543
    93 Integrating Python and R into a Data Analysis Pipeline – Part 1 졸리운_곰 2016.11.16 635
    92 Calling R from Python file 졸리운_곰 2016.11.16 450
    91 [python] BeautifulSoup으로 웹에 있는 데이터 긁어오기 졸리운_곰 2016.11.15 586
    90 파이썬으로 XML 처리하기 졸리운_곰 2016.11.15 388
    89 [python] httplib — HTTP protocol client¶ 졸리운_곰 2016.11.15 548
    88 virtualenv를 사용하자 - 가상 개발환경 구축하기 졸리운_곰 2016.11.13 502
    87 SQLAlchemy 시작하기 – Part 2 졸리운_곰 2016.11.11 610
    86 SQLAlchemy 시작하기 – Part 1 졸리운_곰 2016.11.11 658
    » python torrent 자동 다운로드 : How to automatically search and download torrents with Python and Scrapy 졸리운_곰 2016.11.02 875
    84 Flask에서 SQLAlchemy 사용하기 졸리운_곰 2016.10.30 725
    83 Apache와 Python 연동하기 졸리운_곰 2016.10.16 1612
    82 파이썬으로 개발된 놀라운 라이브러리들! 파이썬 만세! file 졸리운_곰 2016.08.10 7038
    81 윈도우에서 파이썬 설치하기 (virtualenv, pip 사용법) file 졸리운_곰 2016.08.08 1080
    80 [Python] 파이썬 실행환경의 독립 virtualenv & PyCharm file 졸리운_곰 2016.08.08 791
    79 Python virtualenv 사용법(MAC기준,pip사용) file 졸리운_곰 2016.08.08 456
    78 virtualenv를 사용하자 - 가상 개발환경 구축하기 졸리운_곰 2016.08.08 460
    대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
    통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
    대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED