最近做了个微信推送kindle电子书的公众号:kindle免费书库

不过目前电子书不算非常多,所以需要使用爬虫来获取足够书籍。

于是,写了以下这个爬虫,来爬取kindle114的电子书。

值得注意的地方:

当爬取数过大时,由于对方有开启放抓取,会返回一个javascript而非原始的html,所以我使用

的PyV8来执行这段js从而拿到真正的地址。

目前存在的问题:

正则式写得还不够好,毕竟是第一次正式写爬虫:)

无法下载需要购买的附件

爬虫为单线程,爬完整个网站速度慢。我有试过转成多进程,但是貌似由于不能同时登陆,大多数

爬虫进程都无法正常爬取@@

# -*- coding: utf-8 -*-
import urllib2
import re
import requests
import os
import hashlibdef fuckJS(js):import PyV8import re#去掉<script>标签js=js[31:-9]for st in ['window','location',"'assign'","'href'","'replace'"]:equal=re.findall('[_A-Za-z0-9 =]+%s;'%st,js)#找到变量赋值等式if equal==[]:#有可能没有continueelse:equal=equal[0]var=equal.split('=')[0].strip()#找出变量名#把等式干掉js=js.replace(equal,'')#把变量替换成它真正的意思js=js.replace(var,st)#把['xx'] 替换成 .xxjs=js.replace("['%s']"%st.strip("'"),'.%s'%st.strip("'"))#将 window.href= 后的内容踢掉,因为当PyV8只输出最后一个等式的值if re.findall('window\.href=.+',js)!=[]:js=js.replace(re.findall('window\.href=.+',js)[0],'')#删掉location.xxx=js=js.replace('location.href=','').replace('location.replace','').replace('location.assign','')#交给你了-v-ctxt2 = PyV8.JSContext()ctxt2.enter()#print ctxt2.eval(js)trueAddr = ctxt2.eval(js)print trueAddrreturn trueAddrdef downloadMobi(name, url):#去掉windows下不合法的文件名unlawName = '<>/\\|:""*?'for i in unlawName:name = name.replace(i, '')#正则表达式写的不够好导致的问题@@if name.count(' &nbsp;img src=templateyeei_dream1cssyeeidigest_1.gif class=vm alt= title= ') > 0:name = name.split(' &nbsp')[0]+'.mobi'#避免重复下载if os.path.exists('D:\Kindle114SpiderDownload\\' + name):print 'already have', namereturnurl = url.split(' ')[0]s = requests.session()username = '你的用户名'password = '你的密码'passwordMd5 = hashlib.md5(password).hexdigest()data = {'formhash': '23cd6c29', 'referer': '','username': username, 'password': passwordMd5, 'questionid':'0', 'answer':''}res=s.post('http://www.kindle114.com/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LYn7n&inajax=1',data)#res = s.get('http://www.kindle114.com/forum.php?mod=attachment&aid=MTQ2NTB8ZjhkNjY3NmF8MTQxNjg5OTYxOXw0NDIxfDczNjI%3D')try:res = s.get(url, timeout = 200)except:print 'time out for ', name#print 'content[:50]'#print res.content[:50]if res.content.count('<!DOCTYPE html') > 0:print '!!!!!!!!!!!!!!!!!not a mobi, this file need gold coin!!!!!!!!!!!!!!!'returntry:with open('D:\\Kindle114SpiderDownload\\' + name, "wb") as code:code.write(res.content)except:print '!!!!!!!!!!!!!!!!!!!!!遇到不合法文件名!!!!!!!!!!!!!!!!!!', namedef spiderThread(url, threadName):req = urllib2.urlopen(url, timeout = 10)text = req.read()if text.count('<!DOCTYPE html') == 0:js = texttrueURL = 'http://www.kindle114.com/' + fuckJS(js)print 'trueURL', trueURLreq = urllib2.urlopen(trueURL)text = req.read()#href = '<a href="(.*?)" οnmοuseοver="showMenu({\'ctrlid\':this.id,\'pos\':\'12\'})" id=.*?target="_blank">(.*?)</a>'href = '<a href="(.*?)".*?target="_blank">(.*?)</a>'href_re = re.compile(href)href_info = href_re.findall(text)bookSum = 0for i in href_info:if i[1].count('.mobi') > 0:bookSum+=1if bookSum == 0:print '!!!bookSum = 0!!!!', text[:100]if bookSum == 1:print 'only one book in this thread'bookFileName = threadName + '.mobi'for i in href_info:if i[1].count('.mobi') > 0:link = i[0].replace('amp;','')breakprint link, bookFileNamedownloadMobi(bookFileName, link)else:print str(bookSum), 'in this thread'for i in href_info:if i[1].count('.mobi') > 0:link = i[0].replace('amp;','')bookFileName = i[1]print link, bookFileNamedownloadMobi(bookFileName, link)for pageNum in range(1, 125):    url = 'http://www.kindle114.com/forum.php?mod=forumdisplay&fid=2&filter=sortid&sortid=1&searchsort=1&geshi=1&page=' + str(pageNum)print '=============url', url,'==============='try:req = urllib2.urlopen(url, timeout = 10)except:print 'page time out', urltext = req.read()href = '<h4><a href="(.*?)" target="_blank" class="xst">(.*?)<span class="xi1">'href_re = re.compile(href)href_info = href_re.findall(text)for i in href_info:print i[0], i[1]url = 'http://www.kindle114.com/'+i[0]threadName = i[1]try:spiderThread(url, threadName)except Exception , e:print '!!!!!!!!!!!!! Error with ',threadName, url,'!!!!!!!!!!!!!!!!'print e
raw_input('finish all!!!')

转载于:https://www.cnblogs.com/instant7/p/4132836.html

使用Python爬取mobi格式电纸书相关推荐

  1. python爬取m3u8格式视频

    python爬取m3u8格式视频 m3u8原理 脚本环境 爬取步骤 步骤的具体实现 python细节处理说明 参考代码 m3u8原理 当我们在网页播放视频时,网页向服务器发起一个以.m3u8结尾的连接 ...

  2. Python爬取m3u8格式的视频

    声明:本文只作学习研究,禁止用于非法用途,否则后果自负,如有侵权,请告知删除,谢谢! Python爬取m3u8格式的视频目录 背景 1.文件信息 那什么是m3u8呢? 2.构造请求获得m3u8文件 3 ...

  3. python爬取pbf格式的矢量瓦片并转换为shp使用

    一.原理 1.瓦片地图原理:瓦片地图原理- 简书 (jianshu.com) 二.过程 爬取数据 1.找到矢量瓦片服务地址,以及瓦片的请求规则,构造请求url 2.计算瓦片范围,通过查看服务参数信息, ...

  4. Python爬取m3u8格式视频并解密ts文件合并转为mp4格式

    一. m3u8是什么格式 m3u8是苹果公司推出的视频播放标准,是m3u的一种,只是编码格式采用的是UTF-8. m3u8准确来说是一种索引文件,使用m3u8文件实际上是通过它来解析对应的放在服务器上 ...

  5. Python爬取Json格式数据并读写(改中文编码)

    Python Json文件读写 经过测试发现,req.json()返回的类型是dict(字典类型) 如果有兴趣的话,可以再加一个正则表达式来筛选出url的关键名字,用关键名来做文件名. import ...

  6. python爬取json数据_Python爬取数据保存为Json格式的代码示例

    python爬取数据保存为Json格式 代码如下: #encoding:'utf-8' import urllib.request from bs4 import BeautifulSoup impo ...

  7. python爬取电影评分_用Python爬取猫眼上的top100评分电影

    代码如下: # 注意encoding = 'utf-8'和ensure_ascii = False,不写的话不能输出汉字 import requests from requests.exception ...

  8. Python 爬取北京二手房数据,分析北漂族买得起房吗?(附完整源码)

    来源:CSDN 本文约3500字,建议阅读9分钟. 本文根据Python爬取了赶集网北京二手房数据,R对爬取的二手房房价做线性回归分析,适合刚刚接触Python&R的同学们学习参考. 房价高是 ...

  9. python爬取资料_Python爬取FLASH播放器中的资料

    Python爬取FLASH播放器中的资料. 一.首先了解一下AMF协议:AMF(Action Message Format)是Flash与服务端通信的一种常见的二进制编码模式,其传输效率高,可以在HT ...

最新文章

  1. 递归/回溯:subsets求子集
  2. 路径规划(Path Planning)与运动规划(Motion Planning)
  3. 【错误记录】VMware 虚拟机报错 ( 向 VMWare 虚拟机中的 Ubuntu 系统拷贝文件时磁盘空间不足 )
  4. mysqlbinlog 恢复mysql数据
  5. 便携式计算机的工作原理,便携式计算机及控制该计算机的方法
  6. SSH(Spring+Struts2+Hibernate)框架搭建步骤(含配置文件以及运行结果)
  7. JPA / Hibernate:基于版本的乐观并发控制
  8. [html] 使用button当按钮和使用div当按钮有什么区别?
  9. Spring MVC @RequestMapping Annotation示例
  10. 用java写猜拳游戏,Java写人机猜拳游戏(可扩展其他游戏或其他参与者)
  11. 微信小程序中相机api_微信拍照翻译, 使用小程序拍照翻译API功能
  12. cjson构建_利用cJSON解析和创建JSON字符串
  13. 修改apk图标及名字
  14. html5新标签 figure 和 figcaption
  15. 如何去除ul小圆点的html,html里面ul那个点怎么消
  16. 10月份语音合成任务安排: 商业化的普通话合成 (质量, 速度, 准确度, 韵律)
  17. 2022还不知道登陆邮箱账号怎么填写?个人邮箱登录注册流程看详解
  18. 喂养三种宠物:猫、狗和鸟
  19. 知乎大V点赞一个多少费用,知乎大V推广问答发布操作
  20. 星际争霸2免修改器修改绝对一劳永逸

热门文章

  1. 可以扦插的花有哪些?
  2. 真正的蓝海是适合你的领域
  3. 农村新兴致富行业,小家电玩具换旧手机,最多月入几十万
  4. API/POSIX/C库的区别与联系
  5. 12306外包给阿里巴巴、IBM等大企业做是否可行?
  6. linux svn 设置propertise
  7. 游标sql server_学习SQL:SQL Server游标
  8. aws rds监控慢sql_估算AWS RDS SQL Server成本
  9. SQL Server 2016中的新PowerShell Cmdlet
  10. sql server 监视_使用动态管理对象监视SQL Server –会话和连接