2017-06-26 8 views
1

として保存:Pdfファイルこれは私のコードでHTMLファイル - パイソン

import requests 
import time 
from bs4 import BeautifulSoup as bs 
import urllib.request 
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' 
headers={'User-Agent':user_agent,} 
_URL = 'http://papers.xtremepapers.com/CIE/Cambridge%20International%20A%20and%20AS%20Level/Chemistry%20%289701%29/' 

r = requests.get(_URL) 
soup = bs(r.text) 
urls = [] 
names = [] 
for i, link in enumerate(soup.findAll('a')): 
    _FULLURL = _URL + (link.get('href')) 
    if _FULLURL.endswith('.pdf'): 
     urls.append(_FULLURL) 
     names.append(soup.select('a')[i].attrs['href']) 
names_urls = zip(names, urls) 

for name, url in names_urls: 
    print (url) 
    rq = urllib.request.Request(url,None,headers) 
    res = urllib.request.urlopen(rq) 
    pdf = open("pdfs/" + (name), 'wb') 
    pdf.write(res.read()) 
    pdf.close() 
    print("completed") 

PDFがダウンロードしているが、私はそれらを開いたとき、私は error
PSを取得します。私はPythonに新しいので、これがルーキーミスであれば私を許してください

+0

を=オープン(「PDFファイル/」+拡張子がない場合、pdf = open( "pdf /" + name + "。pdf"、 'wb') 'に' –

+0

@DatHydroGuyなぜそうですか?ちょっとビットですので、特別なlibなしでpdfバイナリコンテンツからpdfファイルを作成することができます。 –

+0

@aeratedfrisbee応答ステータスコードとコンテンツタイプヘッダーをチェックして、ディスクに保存する前に期待通りの結果が得られていることを確認する必要があります。 –

答えて

0

あなたのコードのどこに誤りがあるのか​​正確には言えません - おそらくあなたが実際にPDFのURLを構築する方法です最初の賭け) - しかし、Pythonの要求を使用して根のURLのみ( "http://papers.xtremepapers.com")をベースURLとして使用するとうまくいくようです(少なくともコンテンツタイプは期待されるアプリケーション/ pdfです)。次のスクリプトはず作業(マイナスの可能なタイプミスやその他もろもろ - 私はそれらのpdfファイルのxD必要としない、スクリプト全体をテストしていない)たぶん、あなたは `PDFを変えてみてください

import requests 
from bs4 import BeautifulSoup 

ROOT_URL = 'http://papers.xtremepapers.com' 
PAGE_URL = ROOT_URL + '/CIE/Cambridge%20International%20A%20and%20AS%20Level/Chemistry%20%289701%29/' 

page = requests.get(PAGE_URL) 
soup = bs(page.text) 
urls = [] 

for link in soup.findAll('a'): 
    href = link.get('href') 
    if not (href and href.endswith('.pdf')): 
     continue 

    # builds a working absolute url 
    url = ROOT_URL + href 
    # only keeps the filename part as, well, filename 
    name = href.split('/')[-1] 
    print("url: {} - name : {}".format(url, name)) 

    try: 
     r = requests.get(url) 
     # this will raise if not 200 
     r.raise_for_status() 
     # check the content type and raise if not ok 
     if r.headers["Content-Type"] != "application/pdf": 
      raise ValueError("unexpected content type '{}'".format(r.headers["Content-Type"])) 

    except Exception as e: 
     print("{} failed : {}".format(url, e)) 
     continue 

    with open("pdfs/" + (name), 'wb') as pdf: 
     pdf.write(r.content) 
    print("{} ok".format(name)) 

print("Done") 
+0

うん、これはうまくいきました。助けてくれてありがとう! – aeratedfrisbee

関連する問題