个人随笔
目录
Python3爬取笔趣阁完本小说
2019-07-24 23:15:22

Python作为爬虫工具简单方便,这里举个我爬取笔趣阁小说的例子。

所需模块

BeautifulSoup、lxml、urllib
这个的作用是通过url读取html文档以及解析,安装方法可以参考: Python3安装beautifulsoup4和lxml

流程

1、分析笔趣阁https://www.biqiuge.com小说url的结构

通过分析可以知道,笔趣阁每本小说的链接为:https://www.biqiuge.com/book/id/
id为数字,从1开始,比如第一篇https://www.biqiuge.com/book/1/ 以发现是龙符。以后每本小说由数字加上去。

2、用urllib工具访问url返回html页面内容

访问内容我们可以知道,并没有进行任何异步加载,并且是全部章节都显示出来。如果是异步的话,可能需要模拟浏览器,这个以后有时间说明。

3、用BeautifulSoup、lxml解析小说页面,获取所有章节列表以及小说标题

这一步用BeautifulSoup工具来很简单。举个例子如下,有一个html字符串,然后转变为BeautifulSoup对象,然后很方便的解析出标签内容。

  1. soup_texts = BeautifulSoup(html, 'lxml')
  2. texts = soup_texts.find_all(class_="info")
  3. soup_text = BeautifulSoup(str(texts),"lxml")
  4. title = soup_text.find_all("h2")
  5. title=title[0].string
  6. spans = soup_text.find_all("span")

4、用io保存为txt小说

保存之前,这里需要对
换行符都替换成”\n”,因为在txt中,这个才是换行符。

所有代码

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. ##导入爬取模块
  4. from bs4 import BeautifulSoup
  5. from urllib import request
  6. ##根据url获取response
  7. def getResponse(url):
  8. #url请求对象Request是一个类
  9. #如果不加上下面的这行出现会出现urllib2.HTTPError: HTTP Error 403: Forbidden错误 #主要是由于该网站禁止爬虫导致的,可以在请求加上头信息,伪装成浏览器访问User-Agent,具体的信息可以通过火狐的FireBug插件查询 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(url=chaper_url, headers=headers)
  10. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
  11. url_request = request.Request(url=url, headers=headers)
  12. #print(url_request)
  13. #print(url_request.data)
  14. try:
  15. url_response = request.urlopen(url_request)
  16. except Exception as e:
  17. url_response="error"
  18. """
  19. geturl():返回 full_url地址
  20. info(): 返回页面的元(Html的meta标签)信息
  21. <meta>:可提供有关页面的元信息(meta-information),比如针对搜索引擎和更新频度的描述和关键词。
  22. getcode(): 返回响应的HTTP状态代码
  23. 100-199 用于指定客户端应相应的某些动作。
  24. 200-299 用于表示请求成功。
  25. 300-399 用于已经移动的文件并且常被包含在定位头信息中指定新的地址信息。
  26. 400-499 用于指出客户端的错误。
  27. 500-599 用于支持服务器错误。
  28. read(): 读取网页内容,注意解码方式(避免中文和utf-8之间转化出现乱码)
  29. """
  30. return url_response #返回这个对象
  31. #获取这一本书
  32. def getNewBook(sort):
  33. infos = getAllChaptersAndInfo("https://www.biqiuge.com/book/"+str(sort)+"/")
  34. if(infos=="error"):
  35. print("停止")
  36. return "error"
  37. #保存书本信息
  38. books = infos[1]
  39. username=books["username"]
  40. status=books["status"]
  41. title=books["title"]
  42. username = username[3:]
  43. status = status[3:]
  44. if status=="完结":
  45. dealChapters(infos[0],title,username,sort)
  46. else:
  47. return
  48. #获取章节和内容
  49. def getAllChaptersAndInfo(url):
  50. http_reponse = getResponse(url)
  51. if(http_reponse=="error"):
  52. return "error"
  53. html = http_reponse.read()
  54. html = html.decode("gbk",errors="ignore")
  55. list = getChapters(html)
  56. info = getInfo(html)
  57. return [list,info]
  58. #解析html获取章节列表
  59. def getChapters(html):
  60. i = html.find("正文卷")
  61. html=html[i:]
  62. soup_texts = BeautifulSoup(html, 'lxml')
  63. texts = soup_texts.find_all("dd")
  64. soup_text = BeautifulSoup(str(texts),"lxml")
  65. #获得章节列表
  66. html = soup_text.find_all("a")
  67. return html;
  68. def getInfo(html):
  69. soup_texts = BeautifulSoup(html, 'lxml')
  70. texts = soup_texts.find_all(class_="info")
  71. soup_text = BeautifulSoup(str(texts),"lxml")
  72. title = soup_text.find_all("h2")
  73. title=title[0].string
  74. spans = soup_text.find_all("span")
  75. username = spans[0].string
  76. status = spans[2].string
  77. info={"username":username,"title":title,"status":status}
  78. return info
  79. #获取文章列表
  80. def dealChapters(list,booktitle,username,sort):
  81. size = len(list)
  82. print("这次获取的章节数:"+str(size))
  83. book = str(sort)+"-"+booktitle+"-"+username+".txt"
  84. fo = open("./txt/"+book,"a+")
  85. for index in range(size):
  86. #这里是从0开始,但是章节要+1,当章节大于最大章节才开始下载
  87. d = list[index]
  88. title = d.string
  89. print("正在下载:"+title.encode('gbk', 'ignore').decode('gbk'))
  90. href = "https://www.biqiuge.com"+d['href']
  91. text = getChapter(href).replace("\xa0","").replace("<br/>","\n")
  92. try:
  93. fo.write(title+"\n"+text+"\n")
  94. except Exception as e:
  95. print("有异常")
  96. fo.write(title,"有异常")
  97. continue
  98. print("下载完成")
  99. fo.close()
  100. #获取文章内容
  101. def getChapter(url):
  102. http_reponse = getResponse(url)
  103. html = http_reponse.read()
  104. html = html.decode("gbk",errors="ignore")
  105. soup_texts = BeautifulSoup(html, 'lxml')
  106. texts = soup_texts.find_all(id='content', class_='showtxt')
  107. text = str(texts[0]).strip().replace("\r","").replace("\n","")
  108. start = text.find("\">")
  109. end = text.find("https://www")
  110. text=text[start+2:end]
  111. #print(text.encode('gbk', 'ignore').decode('gbk'));
  112. return text
  113. fo = open("sort","r+")
  114. try:
  115. sort = fo.readline()
  116. sort = int(sort.strip().replace("\n",""))
  117. print("已经下载的章节是:"+str(sort))
  118. for i in range(sort,100000):
  119. index= i+1
  120. fo.seek(0)
  121. fo.truncate()
  122. fo.write(str(index))
  123. getNewBook(index)
  124. except Exception as e:
  125. print("下载发生异常,暂停"+str(e))
  126. fo.close()
  127. finally:
  128. fo.close()

上面还记录了加载的小说id,这样子,下次启动就可以直接从最新的id开始,如果只是想要加载某一本小说的话,只需要执行getNewBook(index)即可,index为小说id,这个根据小说名称去笔趣阁搜索,然后链接就可以看到。我这个代码还判断了小说是否是完本小说,毕竟完本小说才方便。

转载请注明来源。

 768

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2