某文库的文档一直要氪金才能下载,还好我会Python,轻松实现白嫖!
基本开发环境????
- Python 3.6
- Pycharm
相关模块的使用????
import os
import requests
import time
import re
import json
from docx import Document
from docx .shared import Cm
安装Python并添加到环境变量,pip安装需要的相关模块即可。
????目标网页分析
网站的文档内容,都是以图片形式存在的。它有自己的数据接口
接口链接:
https://openapi.book118.com/getPreview.html?&project_id=1&aid=272112230&t=f2c66902d6b63726d8e08b557fef90fb&view_token=SqX7ktrZ_ZakjDI@vcohcCwbn_PLb3C1&page=1&callback=jQuery18304186406662159248_1614492889385&_=1614492889486
接口的请求参数
整体思路
- 请求网页返回response数据(字符串)
- 通过re模块匹配提取中间的数据(列表)索引取0(字符串)
- 通过json模块是把提取出来的数据转换成json模块
- 通过遍历获取每张图片的url地址
- 保存图片到本地文件夹
- 把图片保存到word文档
爬虫代码实现
def download():
content = 0 for page in range(1, 96, 6 ): # 给定 2秒延时 time.sleep(2 ) # 获取时间戳 now_time = int(time.time() * 1000 )
url = ' https://openapi.book118.com/getPreview.html ' # 请求参数 params = { ' project_id ' : ' 1 ' , ' aid ' : ' 272112230 ' , ' t ' : ' f2c66902d6b63726d8e08b557fef90fb ' , ' view_token ' : ' SqX7ktrZ_ZakjDI@vcohcCwbn_PLb3C1 ' , ' page ' : f ' {page} ' , ' _ ' : now_time,
} # 请求头 headers = { ' Host ' : ' openapi.book118.com ' , ' Referer ' : ' https://max.book118.com/html/2020/0427/8026036013002110.shtm ' , ' User-Agent ' : ' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 ' }
response = requests.get(url=url, params=params, headers= headers) # 使用正则表达式提取内容 result = re.findall( ' jsonpReturn\((.*?)\) ' , response.text)[0] # 字符串转json数据 json_data = json.loads(result)[ ' data ' ] # 字典值的遍历 for value in json_data.values():
content += 1 # 拼接图片url img_url = ' http: ' + value print (img_url)
headers_1 = { ' Host ' : ' view-cache.book118.com ' , ' User-Agent ' : ' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 ' } # 请求图片url地址 获取content二进制数据 img_content = requests.get(url=img_url, headers= headers_1).content # 文件名 img_name = str(content) + ' .jpg ' # 保存路径 # Python学习交流群:815624229 filename = ' img\\ ' # 以二进制方式保存 (图片、音频、视频等文件都是以二进制的方式保存) with open(filename + img_name, mode= ' wb ' ) as f:
f.write(img_content)
注意点:
1、一定要给延时,不然后面接口数据会请求不到。
2、请求图片url的时候headers参数需要写完整,否则保存图片是无法打开的
3、命名最好是给定数字,1.jpg、2.jpg 这样,方便后续保存到word
爬虫部分的代码还是比较简单的,没有什么特别的难度。
爬取这些文档,都是需要打印或者查询所以要把这些单张的图片都保存到word文档里面。
????写入文档
def save_picture():
document = Document()
path = ' ./img/ ' lis = os.listdir(path)
c = [] for li in lis:
index = li.replace( ' .jpg ' , '' )
c.append(index)
c_1 = sorted(list(map(int, c))) print (c_1)
new_files = [(str(i) + ' .jpg ' ) for i in c_1] for num in new_files:
img_path = path + num
document.add_picture(img_path, width =Cm(17), height=Cm(24 ))
document.save( ' tu.doc ' ) # 保存文档 os.remove(img_path) # 删除保存在本地的图片