2016-12-22 20 views
1

私はpdfファイル(ホワイトペーパー)のためにgoogleを削っており、コンソールにリストされていないファイルとして保存したいと思っています。URLからファイルをダウンロードする(リスト内)

は、ここで私が現在持っているコードです:

import requests, re 
from docopt import docopt 
from bs4 import BeautifulSoup 
from time import time as timer 
from urllib.request import urlopen, urlretrieve, quote 
from urllib.parse import urljoin 

def get_urls(search_string, start): 
    #Empty temp List to store the Urls 
    temp  = [] 
    url   = 'https://www.google.com/search' 
    payload  = { 'q' : search_string, 'start' : start } 
    my_headers = { 'User-agent' : 'Mozilla/11.0' } 
    r   = requests.get(url, params = payload, headers = my_headers) 
    soup  = BeautifulSoup(r.text, 'html.parser') 
    h3tags  = soup.find_all('h3', class_='r') 
    for h3 in h3tags: 
     try: 
      temp.append(re.search('url\?q=(.+?)\&sa', h3.a['href']).group(1)) 
     except: 
      continue 
    return temp 

def main(): 
    start  = timer() 
    #Empty List to store the Urls 
    result = [] 
    arguments = docopt(__doc__, version='MakMan Google Scrapper & Mass Exploiter') 
    search = arguments['<search>'] 
    pages  = arguments['<pages>'] 
    #Calling the function [pages] times. 
    for page in range(0, int(pages)): 
     #Getting the URLs in the list 
     result.extend(get_urls(search, str(page*10))) 
    #Removing Duplicate URLs 
    result = list(set(result)) 
    print(*result, sep = '\n') 
    print('\nTotal URLs Scraped : %s ' % str(len(result))) 
    print('Script Execution Time : %s ' % (timer() - start,)) 
if __name__ == '__main__': 
    main() 


#End 

私が追加しようとした:ファイルにそれを解析する

with open ('file.txt', 'w') as f: 
    print(*result, file=f) 

を最後に、私はダウンロードする簡単な方法があります確信しています最初にファイルへのリンクを保存せずにpdfファイルを作成します。

+3

あなたが見つけたURLごとに 'urlopen'を実行して、内容をファイルに保存しないでください。 –

答えて

2

PDFファイルのURLがある場合は、urllib.urlretrieve()のように使用できます。これはファイルを現在の作業ディレクトリにダウンロードしてその名前を保持します。もちろん、好きなターゲットパスを指定することもできます。

from os import path 
from urllib import urlretrieve 
from urlparse import urlparse 

src_url = 'http://path/to/document.pdf' 
tgt_path = path.split(urlparse(src_url).path)[-1] 
urlretrieve(src_url, tgt_path) 
+0

これはまさに私が探していたものです、ありがとう! 'url_list = url_listにラインの をもたらす:ここ は、私が追加したコードです 試み: src_url =ライン tgt_path = path.split(urlparse(src_url).path)[ - 1] urlretrieve(src_url、tgt_path) を除く: continue' – Spagett

関連する問題