当前位置:   article > 正文

使用Python爬取小说

python爬取小说

爬取网站:http://www.biqugecom.com/

爬取方式:整站爬取,就是把该站所有的小说都爬下来。

本次爬取涉及到的知识点有:

  • Xpath
  • 类的定义及使用
  • requests库的使用

准备工作

安装requests库:

pip3 install requests

安装lxml库:

pip3 install lxml

分析网站:

得到每个分类的页面的链接只有上面箭头指的地方变了下,因此这里使用Python自动生成了分类的链接:

  1. typeLinks = []
  2. for i in range(1, 9):
  3. typeLinks.append('http://www.biqugecom.com/list/%s-1.html' % (str(i)))
  4. print(typeLinks)

结果为:
 

['http://www.biqugecom.com/list/1-1.html', 'http://www.biqugecom.com/list/2-1.html', 'http://www.biqugecom.com/list/3-1.html', 'http://www.biqugecom.com/list/4-1.html', 'http://www.biqugecom.com/list/5-1.html', 'http://www.biqugecom.com/list/6-1.html', 'http://www.biqugecom.com/list/7-1.html', 'http://www.biqugecom.com/list/8-1.html']

之后再根据每个分类的链接,爬取该分类下的小说,分析分类页面小说的Xpath:

通过Xpath 获取到了一本小说的链接。

再根据一本小说的链接爬取该小说的章节链接,首先获取章节的Xpath:

获取到了一章的链接,再根据一章的链接获取小说的文本内容,还是Xpath获取:

 

 获取到小说的文本内容,下面就可以开始爬取内容了,这里先整理一下待爬取的内容的Xpath:

一本小说的Xpath:

//*[@class='media-heading book-title']/a/@href

一章的Xpath:

//*//dd//a/@href

小说内容的Xpath:

//*[@id='content']/text()

话不多说,直接上代码:

  1. import requests
  2. import random
  3. from lxml import etree
  4. import os
  5. # 设置requests库的重连接次数
  6. requests.adapters.DEFAULT_RETRIES = 5
  7. # 爬取的主域名
  8. HOST = 'http://www.biqugecom.com'
  9. # User-Agent
  10. user_agent = [
  11. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"
  12. "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
  13. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
  14. "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
  15. "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
  16. "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
  17. "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
  18. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
  19. "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
  20. "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
  21. "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
  22. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
  23. "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
  24. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
  25. "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
  26. "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
  27. "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
  28. "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
  29. ]
  30. # 爬取一本小说
  31. class ScrapyOne(object):
  32. def __init__(self, rootLink):
  33. super(ScrapyOne, self).__init__()
  34. self.rootLink = rootLink
  35. # 爬取每章的链接
  36. def scrapyLink(self):
  37. try:
  38. # 随机生成请求头
  39. header = {"User-Agent": random.choice(user_agent)}
  40. res = requests.get(self.rootLink, headers=header)
  41. res.encoding = 'gbk'
  42. # 解析HTML
  43. data = etree.HTML(res.text)
  44. links = []
  45. # 获取书名
  46. bookname = data.xpath("//*[@id='info']/h1/text()")[0]
  47. # 获取每章的链接,由于前9个是推荐章节,因此从第10个开始爬
  48. for link in data.xpath("//*//dd//a/@href")[9:]:
  49. links.append(HOST + link)
  50. if links:
  51. return {
  52. 'bookname': bookname,
  53. 'links': links
  54. }
  55. else:
  56. return []
  57. except Exception as e:
  58. print(e)
  59. return []
  60. # 爬取一章的内容
  61. def scrapyText(self, url):
  62. try:
  63. header = {"User-Agent": random.choice(user_agent)}
  64. res = requests.get(url, headers=header)
  65. res.encoding = 'gbk'
  66. data = etree.HTML(res.text)
  67. # 获取章节名
  68. name = data.xpath("//*[@class='bookname']/h1/text()")[0]
  69. texts = []
  70. # 获取小说内容
  71. for text in data.xpath("//*[@id='content']/text()"):
  72. text = text.replace('\r\n', '').replace('\xa0\xa0\xa0\xa0', '')
  73. if text:
  74. texts.append(text)
  75. if texts:
  76. return {
  77. 'name': name,
  78. 'texts': texts
  79. }
  80. else:
  81. return False
  82. except Exception as e:
  83. print(e)
  84. return False
  85. # 保存一章
  86. def save(self, bookname, name, texts):
  87. try:
  88. # 文件夹不存在则以小说名字创建
  89. if not os.path.exists('./' + bookname):
  90. os.makedirs('./' + bookname)
  91. with open('./%s/%s.txt' % (bookname, name), 'w', encoding='UTF - 8 - sig') as f:
  92. f.write(name + '\n')
  93. for text in texts:
  94. f.write(text + '\n')
  95. f.close()
  96. return True
  97. except Exception as e:
  98. print(e)
  99. return False
  100. # 主函数
  101. def main(self):
  102. try:
  103. # 获取书的章节信息
  104. bookInfo = self.scrapyLink()
  105. # 这里的i主要是为了方便爬取出的小说在资源管理器好排序
  106. i = 0
  107. for link in bookInfo['links']:
  108. # 获取一章的内容
  109. info = self.scrapyText(link)
  110. if info:
  111. if self.save(bookInfo['bookname'], str(i) + '-' + info['name'], info['texts']):
  112. print('存储成功', info['name'])
  113. else:
  114. print('存储失败', info['name'])
  115. i += 1
  116. except Exception as e:
  117. print(e)
  118. # 获取每个分类下的小说链接
  119. def scrapyRootLink(url):
  120. try:
  121. header = {"User-Agent": random.choice(user_agent)}
  122. res = requests.get(url, headers=header)
  123. res.encoding = 'gbk'
  124. data = etree.HTML(res.text)
  125. links = []
  126. for link in data.xpath("//*[@class='media-heading book-title']/a/@href"):
  127. if link:
  128. links.append(link)
  129. if links:
  130. print('分类已完毕 %s' % (url))
  131. return links
  132. else:
  133. return []
  134. except Exception as e:
  135. print(e)
  136. return []
  137. if __name__ == "__main__":
  138. typeLinks = []
  139. # 生成分类链接
  140. for i in range(1, 9):
  141. typeLinks.append('http://www.biqugecom.com/list/%s-1.html' % (str(i)))
  142. for typeLink in typeLinks:
  143. # 根据分类链接
  144. for rootLink in scrapyRootLink(typeLink):
  145. # 爬取一本小说
  146. one = ScrapyOne(rootLink)
  147. one.main()

程序运行结果:

  1. 分类已完毕 http://www.biqugecom.com/list/1-1.html
  2. 存储成功 第一章 小生来也
  3. 存储成功 第二章 过河拆桥
  4. 存储成功 第三章 仙子落难
  5. 存储成功 第四章 偷鸡的贼
  6. 存储成功 第五章 后会有期
  7. 存储成功 第六章 有人带路
  8. 存储成功 第七章 有辱斯文
  9. 存储成功 第八章 撒回野吧
  10. 存储成功 第九章 同道中人
  11. 存储成功 第十章 什么意思
  12. 存储成功 第十一章 令师何人
  13. 存储成功 第十二章 此道漫漫
  14. 存储成功 第十三章 诸位慢行
  15. 存储成功 第十四章 御风而行
  16. 存储成功 第十五章 怪物凶猛
  17. 存储成功 第十六章 也很吓人
  18. 存储成功 第十七章 做梦来着
  19. 存储成功 第十八章 很不简单
  20. 存储成功 第十九章 天刑符经
  21. 存储成功 第二十章 灵山有路
  22. 存储成功 第二十一章 故人寻来
  23. 存储成功 第二十二章 图的个啥
  24. 存储成功 第二十三章 灵山仙缘
  25. ......

查看爬取的小说:

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号