book118可预览文档下载@TOC

book118可预览文档下载

最早从csdn上搜到的book118可预览文档下载方法是js代码,很简短的一段,然后在开发者工具里使用。按步骤一回车即可下载。

function download(url, fileName) {let xhr = new XMLHttpRequest();xhr.open('GET', url, true);//true表示异步xhr.responseType = 'blob';xhr.onload = () => {if (xhr.status === 200) {downloadByA(xhr.response,fileName);}};xhr.send();
}
function downloadByA(data,fileName){let urlObject = window.URL || window.webkitURL || window;let export_blob=new Blob([data]);let a=document.createElement("a");a.href=urlObject.createObjectURL(export_blob);a.download=fileName;a.click();
}
//下面这块代码需要按自己需求,进行稍微地修改,上面两块代码可以不用动
document.querySelectorAll(".pageBox img").forEach(function(ele, i) {download(ele.src,i+".jpg");
});

原文链接在这里文章链接

但是使用以后发现有问题,文件页数一多就出现缺页情况。
再次搜索发现了python实现的代码。
Py3 下载book118预览图片并合并成docx文件文章链接
就拷贝测试了一下,发现作者的源码有问题,然后进行了部分更正,和格式调整。
中间除了点list和函数间调用时的bug。
然后增加了用pymupdf 模块 生产pdf文件的步骤,毕竟pdf更方便的多,反正下载的也是不可编辑的png图片。

#!/usr/bin/env python
# coding: utf-8# In[1]:# -*- coding: utf-8 -*-# In[2]:import requests# In[3]:import json# In[4]:import re# In[5]:import time# In[6]:import os# In[7]:import sys# In[8]:import lxml# In[9]:from bs4 import BeautifulSoup# In[10]:from docx import Document# In[11]:from docx.shared import Cm# In[12]:import glob# In[13]:import fitz# In[14]:headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'}# In[15]:mylist=[]# In[16]:#定义保存地址# In[17]:def path1():path1=input('please input path:')if len(path1)< 2:path1 = 'C:\\tmp'if os.path.exists(path1) == False:os.makedirs(path1)mylist.append(path1)# In[18]:#len(path1)# In[19]:#获取真实预览地址turl
def turl():url = input('please input url:')if len(url)<10:url = 'https://max.book118.com/html/2017/0323/96553980.shtm'aid = re.search('\d{1,100}\.s',url).group()[:-2]rep = requests.get(url, headers=headers)soup = BeautifulSoup(rep.content, 'lxml', from_encoding='utf-8')title = soup.title.contents[0]title = title[:title.find('.')]#time.sleep(2)turl = 'https://max.book118.com/index.php?g=Home&m=NewView&a=index&aid={}'.format(aid)#print('turl:',turl)mylist.append(turl)mylist.append(title)#print(mylist)# In[20]:def bookinfo():turl()#获取预览信息,放在book中rep2 = requests.get(mylist[1], headers=headers)#time.sleep(8)if '验证' in rep2.text:print('need verify')print(rep2.text)else:bs = BeautifulSoup(rep2.content,'lxml', from_encoding='utf-8')for i in bs.find_all('script'):js = i.stringif js is not None and 'PREVIEW_PAGE' in js:p1 = re.compile(".+?'(.+?)'")js_line = js.splitlines(1)book = {'pageAll':p1.findall(js_line[1])[0],'pagePre':p1.findall(js_line[1])[1],'aid':p1.findall(js_line[7])[0],'viewToken':p1.findall(js_line[7])[1],'title':mylist[2]}print("ok")     else:print("")print('book:',book)mylist.append(book)# In[21]:def prepage_url():#利用book中的信息获取预览图片地址,放在url_dict中page = {'max':int(mylist[3]['pageAll']),'pre':int(mylist[3]['pagePre']),'num':1,'repeat':0}  #设置循环,尽量获取全部预览图片的地址url3_dict = {}while page['num'] < page['pre']:        url3 = 'https://openapi.book118.com/getPreview.html' playload = {'project_id': 1,'aid': mylist[3]['aid'],  'view_token': mylist[3]['viewToken'], 'page': page['num']}rep3 = requests.get(url3, params=playload, headers=headers)    rep3_dict = json.loads(rep3.text[12:-2])    if rep3_dict['data'][str(page['num'])]:url3_dict.update(rep3_dict['data'])page['num'] = page['num'] + 6time.sleep(3)page['repeat'] = 0else:if page['repeat'] > 6:sys.stdout.write('\r{0}'.format(str(page['num']) + " : Repeat too much.\n !get nothing, sleep 5 second."))sys.stdout.flush()time.sleep(3)else:sys.stdout.write('\r{0}'.format(str(page['num']) + " : !get nothing, sleep 2 second."))sys.stdout.flush()time.sleep(3)page['repeat'] = page['repeat'] + 1print(url3_dict) mylist.append(url3_dict)# In[22]:def download():#指定文件夹pathpath=mylist[0] + '/{}'.format(mylist[2])if os.path.exists(path) == False:os.makedirs(path)#下载预览图片到path,并合并到docx文件myDocx = Document()for section in myDocx.sections:section.page_width = Cm(21)section.page_height = Cm(29.7)section.left_margin = section.right_margin = section.top_margin = section.bottom_margin = Cm(0)for item in mylist[4]:try:num = 'Page{:0>3}'.format(item)url_item=mylist[4][item]url_item=url_item[url_item.index('view'):]url = 'http://' + url_item#根据url_dict内url的完整度进行调整print('url:',url,';')rep = requests.get(url, headers=headers)img_filename = path + '/{}.png'.format(num)with open(img_filename, 'wb') as img:img.write(rep.content)print('Saved locally img_filename:',img_filename)myDocx.add_picture(img_filename, width=Cm(21))except:print('{} download wrong'.format(item))myDocx.save('{}.docx'.format(mylist[2]))mylist.append(path)return# In[23]:def pic2pdf():doc = fitz.open( )path=mylist[5]+"/*"#print(mylist[5])a1=len(mylist[0]) + 1name=mylist[5][a1:]+".pdf"print(name)for img in sorted(glob.glob(path)):assert isinstance(img, object)#print(img)imgdoc = fitz.open(img)pdfbytes = imgdoc.convertToPDF()imgpdf = fitz.open("pdf", pdfbytes)doc.insertPDF(imgpdf)if os.path.exists(name):os.remove(name)doc.save(name)doc.close()# In[24]:def main():    path1()bookinfo()prepage_url()download()print('all done')number = input('是否需要输出pdf:(是打1,否打其他)')if int(number) == 1:pic2pdf()print("pdf's done")else:print('88')# In[25]:if __name__ == '__main__':main()

用到的模块包括
requests
json
re
time
os
sys
lxml
bs4
python-docx
pymupdf

为了好看,把代码分成了五个函数。其实不做成函数也一样用,还更简单些,不会出莫名其妙的麻烦。

图片存放地址是path1(默认定义的是c盘tmp目录)下,会根据下载的文档名称生成新的子目录。
下载的doc和pdf文件会在程序本地。
ps:1.windows下""在路径里会出错。
2.{}。format()是一种字符串格式化的方法。
3.跨函数调用的时候,return值会缺少某些属性
4.python在识别路径的时候对\和/都很友好。

下一步加一个界面。
用pyinstaller 打包的时候 跑到另一个xp的机器上测试,结果发现了一个错误
pil/_imaging.cp38-win32.pyd文件找不到。
因为其他电脑都装了python,暂时还没去处理这个问题。回头再继续debug。

测试了一个195页的文件,没有出现错误。

book118可预览文档下载相关推荐

  1. [SWF]在线预览文档下载

    写本文的缘由:领导有些项目文档需要审阅,网站上的文档只能在线预览,没有提供下载.开始用截屏的方式,可想而知这将会是多大的重复性劳动.所以研究了一下,发现可以曲线救国,所以在这里分享一下. 问题描述:这 ...

  2. 在线预览文档 Office Online

    前言 一直想学习做个在线预览文档的功能,今天使用Office Online Server 2016进行实现在线预览功能. 服务器版本选择:Office Online Server 2016搭配wind ...

  3. 【板栗糖GIS】怎么将网络上只能在线预览文档另存为pdf(插件篇)

    怎么将网络上只能在线预览文档另存为pdf(插件篇) 目录 1.使用插件,这里推荐FireShot,好用免费 2.安装该插件的方式 3.打开在线预览文档的网址 4.点击插件-截取整个页面并且-另存为pd ...

  4. OpenOffice在线预览文档

    使用OpenOffice在线预览文档 开发中遇到了一个需求,需要在线预览word文档,excel表格,pdf等等文件,于是经过一圈Google,发现了这个工具,openoffice会把文档转为pdf文 ...

  5. java实现openoffice在线预览文档

    1.openoffice需要导入的jar包 jodconverter-core-3.0-beta-4.jar juh-3.2.1.jar jurt-3.2.1.jar ridl-3.2.1.jar u ...

  6. html怎么转换到百度,类似百度文库在线预览文档flash版(支持word、excel、ppt、pdf)+在线预览文档html版...

    类似百度文库在线预览文档flash版(支持word.excel.ppt.pdf)+在线预览文档html版 (1).将文档转换为html,只支持支持office文档 (2).将文档转换为flash,实现 ...

  7. 前端页面预览word_前端实现在线预览文档

    前端实现在线预览文档 发布时间:2019-06-03 17:22, 浏览次数:529 <>前端实现在线预览文档 最近项目开发中需要实现在线预览Word,Excel,PowerPoint格式 ...

  8. nopi word to html,C# 基于NPOI+Office COM组件 实现20行代码在线预览文档(word,excel,pdf,txt,png)...

    由于项目需要,需要一个在线预览office的功能,小编一开始使用的是微软提供的方法,简单快捷,但是不符合小编开发需求, 就另外用了:将文件转换成html文件然后预览html文件的方法.对微软提供的方法 ...

  9. PHP 在线预览文档

    PHP 在线预览word.excel.ppt.pdf.txt等文档文件. PHP 在线预览文档 写代码比较少的方案. // PDF.text可以直接网页打开查看 // word.excel.ppt 文 ...

  10. 前端实现在线预览文档

    前端实现在线预览文档 最近项目开发中需要实现在线预览Word,Excel,PowerPoint格式的文档,网上查找了很多资源,各说纷纭,但是在一一尝试之后只有使用微软的预览接口才能成功,其他的会出现各 ...

最新文章

  1. 魔尺变机器人_百变魔尺——创意生活
  2. tf.keras.layers.Embedding 嵌入层 示例
  3. [ucgui] 对话框7——按钮触发与模式窗口
  4. XGBoost、LightGBM的详细对比介绍
  5. java语言修饰符$_Java语言中的修饰符
  6. linux vi/vim使用
  7. 老鼠的求爱之旅 (DP)
  8. TortoiseHg使用(hg mercurial repository management)
  9. oracle11g约束有哪几种状态,【简答题】数据完整性通常有哪几种类型, Oracle11g 通过哪些方式来进行数据完整性控制...
  10. 798·锣鼓巷·牛街
  11. python 单链表查找元素_如何在python中一次找到链表的中间元素?
  12. The file contains a character that cannot be represented in the current code pag
  13. WIN10 64位 JDK的安装
  14. 静态代理和动态代理的区别
  15. Json格式乱码处理方式
  16. 晶振知识,及晶振振荡电路
  17. 经典谢幕千千静听(最终版本)7.0.4 去广告增强版下载
  18. UI设计中聊天气泡框的设计技巧
  19. 基于STM32F407使用ADC采集电压实验
  20. SkeyeVSS森林防火远程监控解决方案

热门文章

  1. android加载海康威视(萤石sdk)摄像头
  2. 小米路由老毛子 潘多拉Padavan 无线桥接中继
  3. python发送多人邮件没有展示收件人问题的解决方法
  4. 360急速浏览器有道词典屏幕取词问题
  5. JAVA代码实现抖音转载视频无水印视频,亲测通过
  6. RDP报表工具v2.3报表使用
  7. JSON格式转换工具
  8. 注册测绘师学习笔记7
  9. AD库文件(元件库+封装库+3D模型)
  10. ts html导出excel,用Angular2在客户端导入导出Excel