【问题标题】:Pdf file saving as html file- pythonpdf文件另存为html文件-python
【发布时间】:2017-06-26 07:08:27
【问题描述】:

这是我的代码:

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新手,如果这是菜鸟的错误,请原谅我

【问题讨论】:

  • 如果您缺少扩展名,也许您应该尝试将pdf = open("pdfs/" + (name), 'wb') 更改为pdf = open("pdfs/"+name+".pdf", 'wb')
  • @DatHydroGuy 为什么会这样?有点是有点,所以当然你可以从没有任何特殊库的pdf二进制内容创建一个pdf文件。
  • @aeratedfrisbee 您应该检查响应状态代码和内容类型标头,以确保在将其保存到磁盘之前获得所需的内容。
  • @bruno-desthuilliers 你是对的!我完全错过了原始文件已经是 .pdf 格式 - 我认为这是我们正在谈论的 HTML 到 PDF 的转换。我已经删除了我原来的评论以避免混淆。道歉。
  • @brunodesthuilliers 我该怎么做?

标签: python html pdf beautifulsoup python-requests


【解决方案1】:

我不能确切地说出你的代码中的错误在哪里——可能是你实际构建 pdf url 的方式(或者至少那是我的第一个赌注)——但是使用 python-requests 并仅使用根 url( “http://papers.xtremepapers.com”)作为基本 url,它似乎工作正常(至少内容类型是预期的应用程序/pdf)。以下脚本应该工作(减去可能的拼写错误和诸如此类的东西 - 我没有测试整个脚本,不需要那些 pdf xD)

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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多