当前位置:   article > 正文

使用python简单的抓取网络小说_小说抓取

小说抓取

在读完kcl的语言班后,终于有了大块的空闲时间,想着写一点程序练练手,就花费一点时间写了一个python的小爬虫,很简单,上代码。

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Sep 9 15:28:23 2021
  5. 目的:爬取网络小说文本
  6. @author: fanzhen
  7. """
  8. import requests
  9. from bs4 import BeautifulSoup
  10. import time
  11. def get_html(url):
  12. headers={
  13. 'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
  14. }
  15. req=requests.get(url,headers=headers)
  16. if req.status_code == 200:
  17. req.encoding=req.apparent_encoding #使用网页现在的编码形式,以防乱码
  18. return req.text
  19. #这是判断网页返回的状态码,200代表连接成功,大家常见的应该是404和503
  20. else:
  21. return
  22. def get_texts(html):
  23. soup=BeautifulSoup(html,'html.parser') #使用beautisoup对网页源码进行解析
  24. title=soup.select("#main > h1")#取得章节名称
  25. w=''
  26. w+=title[0].get_text().replace('\n','').replace('\r','')+'\n'
  27. t=soup.find_all('p')
  28. for i in range(len(t)-1): #取得正文
  29. w+=t[i].get_text().replace('\n','').replace('\r','')
  30. w+='\n'
  31. print(w)
  32. return w
  33. def next_page(html):
  34. soup=BeautifulSoup(html,'html.parser') #使用beautisoup对网页源码进行解析
  35. np=soup.select('a')
  36. return np[-1].get('href')
  37. def main():
  38. time_start=time.time()
  39. with open('青囊尸衣.txt','w')as f:
  40. url='https://www.tianyabooks.com/horror/qingnangshiyi/107556.html'
  41. html=get_html(url)
  42. while next_page(html)!='./':
  43. f.write(get_texts(html))#将抓取到的文本放入txt中
  44. url='https://www.tianyabooks.com/horror/qingnangshiyi/'+next_page(html)#取得下一页的网址
  45. html=get_html(url)
  46. time_end=time.time()#监视程式运行总时间
  47. print('抓取完毕,用时:',time_end-time_start,'s')
  48. if __name__=='__main__':
  49. main()

这个小爬虫是单线程的,所以很慢,抓取一本网络小说花费时间大概在5分钟左右,还需要改进。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/825092
推荐阅读
相关标签
  

闽ICP备14008679号